I’m not sure how to explain this, but here it goes:
I am trying to create properties for a JSON file from a DataGridView. I’m using newtonsoft to handle the JSON serializing.
Essentially, the user will add their values to two columns and those values will be turned into properties. Let’s say the user puts in values 10, 20, 30 in Column1, and then in Column2 they put in "A" "B" "C", the resulting JSON should then be:
prompt_map: {
"10": "A"
"20": "B"
"30": "C"
}
And it should keep going depending on how many rows the user creates.
I thought I would share my code, however I’m not sure if it would help because I’m not even sure how to approach this.
The values will go in the prompt_map string as a nest
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myJson As JsonStructure
myJson = New JsonStructure
myJson.prompt_map
Dim myString As String
myString = JsonConvert.SerializeObject(myJson, Formatting.Indented)
MsgBox(myString) 'debugging
End Sub
Public Class JsonStructure
Public prompt_map As Frames
End Class
Public Class Frames
'CODE GOES HERE?
End Class
This is the method I’m using to pull the data from the DataGridView by the way:
Dim colFrames As String
For i = 0 To DataGridView1.RowCount - 1
If Not (DataGridView1.Rows(i).Cells("Column1").Value = 0) Then
colFrames = colFrames + vbNewLine + (DataGridView1.Rows(i).Cells("Column1").Value)
End If
Next
Dim colDesc As String
For i = 0 To DataGridView1.RowCount - 1
If Not (DataGridView1.Rows(i).Cells("Column2").Value = 0) Then
colDesc = colDesc + vbNewLine + (DataGridView1.Rows(i).Cells("Column2").Value)
End If
Next
Again, not sure how useful this is, just showing my attempt.
Any help would be greatly appreciated. I’ve been going at this for most of the day.
2
Answers
One option is to process the rows via a loop into a
Dictionary(Of String, String)
, and then use Newtonsoft to serialize the dictionary.But for that much work, you might be as well off remembering that JSON is just a string, cutting out the middleware, and building the result directly via StringBuilder or similar. Additionally, the Dictionary method wouldn’t allow for duplicate keys, which, while dubiously-legal, could be possible with user-entered data.
You can use a
DataTable
as yourDataGridView.DataSource
, and also the NewtownsoftJObject
class to have dynamic JSON node names.