Home > database >  How to get data from a JSON and display in grid via vb6
How to get data from a JSON and display in grid via vb6

Time:07-23

I need to get data from a JSON-Object and display some data into MSHFlexGrid. I'm using (VBA-JSON v2.3.1 JsonConverter). VBA-Json in Github

Here is the json :

{
"status": "OK",
"code": "OK",
"message": "Ok",
"data": {
"messages": [
{
"number": " 9710001529",
"message": "Hello World",
"sender": " 97911308600",
"time": "2022-07-12T20:12:14Z",
"type": "normal"
},
{
"number": " 9710001529",
"message": "Just For Test",
"sender": " 979051931024",
"time": "2022-06-28T23:15:22Z",
"type": "normal"
},
{
"number": " 9710001529",
"message": "Test",
"sender": " 979565547989",
"time": "2022-01-28T16:04:50Z",
"type": "mobilepanel"
},
{
"number": " 9710001529",
"message": "Comment",
"sender": " 979102900089",
"time": "2018-06-16T22:23:23Z",
"type": "normal"
}
]
},
"meta": {
"total": 37,
"pages": 4,
"limit": 10,
"page": 0,
"prev": null,
"next": "http://0.0.0.0:80/v1/inbox?limit=10\u0026page=1"
}
}

Here my code :

Set Json = JsonConverter.ParseJson(strResp)
MSHFlexGrid1.AddItem Json("data")("messages")(1)("number") & vbTab & Json("data")("messages") 
(1)("message") & vbTab & Json("data")("messages")(1)("sender")

The problem is that only the first row of the table is filled with json's data and there is no title for each column. How can I read the json and display them in the MSHFlexGrid as rows and columns with the name of each column? many thanks

CodePudding user response:

Would something like this work? Long lines broken for clarity. Notice the header is added separately and MANUALLY, before the loop. Second thing to note is that instead of doing Json("data")("messages")(1), you are using your loop variable I with Json("data")("messages")(I). You get the number of messages with .Count, and loop over them. This prevents them from being repeated.

You may or may not have to something like MSHFlexGrid1.Rows = MSHFlexGrid1.Rows 1, depending on your grid type, if it simply shows one row. Unsure on that particular grid control.

Set Json = JsonConverter.ParseJson(strResp)
Dim Header as String
Header = "Number" & vbTab & "Message" & vbTab & "Sender"
MSHFlexGrid1.AddItem Header

For I = 1 to Json("data")("messages").Count
  Dim Line as String
  Line = ""
  Line = Json("data")("messages")(I)("number")
  Line = Line & vbTab 
  Line = Line & Json("data")("messages")(I)("message")
  Line = Line & vbTab 
  Line = Line & Json("data")("messages")(I)("sender")

  MSHFlexGrid1.AddItem Line
Next
  • Related