Android Tutorial Android JSON tutorial

Status
Not open for further replies.
JSON format is a a format similar to XML but usually it is shorter and easier to parse.
Many web services now work with JSON. JSON official site: JSON

Using the new JSON library, you can parse and generate JSON strings easily.

As an example we will parse a the following JSON string:
B4X:
{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}
This example was taken from json.org/examples.
Curl brackets represent an object and square brackets represent an array.
Objects hold key/value pairs and arrays hold list of elements. Commas separate between elements.

In this example, the top level value is an object. This object contains a single object with the key "menu".
The value of this object is another object that holds several elements.
We will get the "menuitem" element, which holds an array of objects, and print the values of the "value" element.

After parsing the string, JSON objects are converted to Maps and JSON arrays are converted to Lists.
We will read this string from a file added by the files manager (Files tab).
B4X:
    Dim JSON As JSONParser
    Dim Map1 As Map
    JSON.Initialize(File.ReadString(File.DirAssets, "example.json"))
    Map1 = JSON.NextObject
    Dim m As Map 'helper map for navigating
    Dim MenuItems As List
    m = Map1.Get("menu")
    m = m.Get("popup")
    MenuItems = m.Get("menuitem")
    For i = 0 To MenuItems.Size - 1
        m = MenuItems.Get(i)
        Log(m.Get("value"))
    Next
JSON.NextObject parses the string and returns a Map with the parsed data. This method should be called when the top level value is an object (which is usually the case).
Now we will work with Map1 to get the required values.
We declare an additional Map with the name 'm'.
B4X:
m = Map1.Get("menu")
The object that maps to "menu" is assigned to m.
B4X:
m = m.Get("popup")
The object that maps to "popup" is now assigned to m.
B4X:
MenuItems = m.Get("menuitem")
The array assigned to "menuitem" is assigned to the MenuItems list.
We will iterate over the items (which are maps in this case) and print the values stored in the elements with "value" key.
B4X:
    For i = 0 To MenuItems.Size - 1
        m = MenuItems.Get(i)
        Log(m.Get("value"))
    Next
The output in the LogCat is:
New
Open
Close

Generating JSON strings is done in a similar way. We create a Map or a List that holds the values and then using JSONGenerator we convert it to a JSON string:
B4X:
    Dim Data As List
    Data.Initialize
    Data.Add(1)
    Data.Add(2)
    Data.Add(3)
    Data.Add(Map1) 'add the previous map loaded from the file.
    Dim JSONGenerator As JSONGenerator
    JSONGenerator.Initialize2(Data)
    Msgbox(JSONGenerator.ToPrettyString(2), "")
JSONGenerator can be initialized with a map or a list.
Converting the data to a JSON string is done by calling ToString or ToPrettyString. ToPrettyString adds indentation and is easier to read and debug.

json_1.png


A tool to help you with working with JSON strings: https://b4x.com:51041/json/index.html
 

Attachments

  • JSONExample.zip
    5.2 KB · Views: 5,915
Last edited:

bluedude

Well-Known Member
Licensed User
Longtime User
It is valid but I just copied in object arrays. I'm having trouble to determine how to create object arrays [] when needed See for example below:

"total": [
{
"price": 85,
"name": "myname",
"value": "aname"
}
],
"shipping": [
{
"price": 80,
"name": "through",
"value": "empty"
}
]

Can this all be done with arrays and CreateMap?
 

pjetson

Member
Licensed User
Longtime User
If I put a URL into a JSON object from a B4A app, the slashes in the URL are escaped with backslashes.

For example, if I have this URL:

http://maps.google.com/?q=-37.9033777,145.0354729

and put it into a JSON string, it comes out like this:

http:\/\/maps.google.com\/?q=-37.9033777,145.0354729

I can't see anywhere that describes this behaviour - is it part of the JSON standard, or is it a convention to try to stop bad things from happening?
 

vincentehsu

Member
Licensed User
Longtime User
Can someone point me in a direction of a tutorial that will help me parse this JSON string
B4X:
{"QueryUpdateResult":"[{\"TXNCode\":\"TXN_QUERY_Q001\",\"MerchantID\":\"00000001\",\"MerchantName\":\"Poskitz Ltd\",\"HardwareID\":\"B8:5E:7B:07:43:92\",\"UpdateTime\":\"2015\/1\/16 下午 01:53:56\",\"DeviceUser\":\"Vincent\",\"Version\":\"New 1.0\",\"isSuccees\":\"1\",\"TypeDesc\":\"NewAPP or APPUpdate\",\"MAC\":\"\",\"Message\":\"Success\"},{\"TXNCode\":\"TXN_QUERY_Q001\",\"MerchantID\":\"00000001\",\"MerchantName\":\"Poskitz Ltd\",\"HardwareID\":\"8C:DE:52:6A:18:9F\",\"UpdateTime\":\"2015\/1\/16 下午 01:54:23\",\"DeviceUser\":\"Vincent\",\"Version\":\"V5V7\",\"isSuccees\":\"1\",\"TypeDesc\":\"TerminalUpdate\",\"MAC\":\"\",\"Message\":\"Success\"}]"}
I've try many times but still not get it
 
Last edited:

fishwolf

Well-Known Member
Licensed User
Longtime User
For external reason i can receive a string, but not is my json, for example can be the html with error.

Now my application crashed, i want add a check on json validiation

how to i can validate the json buffer with b4a function?

Thanks
 

engvidal

Member
Licensed User
Longtime User
Hi.
How can I read only the first 'block' of data from a web based json:

http://thethingsnetwork.org/api/v0/nodes/02015510/

Just the 2 first blocks...

[
{
"snr":9.5,
"gateway_eui":"0080000000009F69",
"node_eui":"02015510",
"data_raw":"QBBVAQKAOQA60NlBIuXL8Q==",
"data":"AqBY",
"rssi":-90,
"datarate":"SF7BW125",
"time":"2016-03-02T14:27:48.817Z",
"frequency":902.899963
},
{
"snr":9.3,
"gateway_eui":"0080000000009F69",
"node_eui":"02015510",
"data_raw":"QBBVAFER45aA60NlBIuXL8Q==",
"data":"AqBZ",
"rssi":-92,
"datarate":"SF7BW125",
"time":"2016-03-02T14:27:12.017Z",
"frequency":902.899162
},
.
.
.
]

Thanks
 

DonManfred

Expert
Licensed User
Longtime User
[
{
"snr":9.5,
"gateway_eui":"0080000000009F69",
"node_eui":"02015510",
"data_raw":"QBBVAQKAOQA60NlBIuXL8Q==",
"data":"AqBY",
"rssi":-90,
"datarate":"SF7BW125",
"time":"2016-03-02T14:27:48.817Z",
"frequency":902.899963
},
{
"snr":9.3,
"gateway_eui":"0080000000009F69",
"node_eui":"02015510",
"data_raw":"QBBVAFER45aA60NlBIuXL8Q==",
"data":"AqBZ",
"rssi":-92,
"datarate":"SF7BW125",
"time":"2016-03-02T14:27:12.017Z",
"frequency":902.899162
},
.
.
.
]
Is not a valid json. Remove the last dots

[
{
"snr":9.5,
"gateway_eui":"0080000000009F69",
"node_eui":"02015510",
"data_raw":"QBBVAQKAOQA60NlBIuXL8Q==",
"data":"AqBY",
"rssi":-90,
"datarate":"SF7BW125",
"time":"2016-03-02T14:27:48.817Z",
"frequency":902.899963
},
{
"snr":9.3,
"gateway_eui":"0080000000009F69",
"node_eui":"02015510",
"data_raw":"QBBVAFER45aA60NlBIuXL8Q==",
"data":"AqBZ",
"rssi":-92,
"datarate":"SF7BW125",
"time":"2016-03-02T14:27:12.017Z",
"frequency":902.899162
}
]

B4X:
Dim parser As JSONParser
parser.Initialize(<text>)
Dim root As List = parser.NextArray
For Each colroot As Map In root
Dim rssi As Int = colroot.Get("rssi")
Dim data_raw As String = colroot.Get("data_raw")
Dim data As String = colroot.Get("data")
Dim snr As Double = colroot.Get("snr")
Dim node_eui As String = colroot.Get("node_eui")
Dim datarate As String = colroot.Get("datarate")
Dim time As String = colroot.Get("time")
Dim gateway_eui As String = colroot.Get("gateway_eui")
Dim frequency As Double = colroot.Get("frequency")
Next

See http://basic4ppc.com:51042/json/index.html
 
Status
Not open for further replies.
Top