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: 6,088
Last edited:

Opengatebr

Member
Licensed User
hi Erel,

we are having an issue when trying to deserialize this json (ResultJson) ...

{ "AdminGateWebLink":"http://qa.app.opengatebr.com/CompanyGate",
"AdminUserWebLink":"http://qa.app.opengatebr.com/User",
"ECommerceLink":"http://www.opengatebr.com/#!loja-e-carrinho/cq49",
"GateList": [
{"Id":102,"Name":"as","Url":"21321","Latitude":0,"Longitude":0},
{"Id":105,"Name":"olabug","Url":"189.54.67.252","Latitude":0,"Longitude":0},
{"Id":106,"Name":"pteste01","Url":"189.54.64.75","Latitude":0,"Longitude":0}
]
}


the b4a debug interface stop the debug when we try to watch the parsed map object.

below follow the code implementation :

Sub ParseResponse(ResultJson As String)
Dim ResponseClassMap As Map

Globals.JsonParser.Initialize(ResultJson)

ResponseClassMap = Globals.JsonParser.NextObject

Dim Gates As List = ResponseClassMap.Get("GateList") 'OK
Dim tempvar1 As List = Gates.Get(1) 'OK
Dim tempvar2 As Object = Gates.Get(1) 'NOK - Error here trying to get innerMap key
End Sub


thank you in advice.

waiting your response,
opengate team
 

DonManfred

Expert
Licensed User
Longtime User
1. Use code tags when posting code!
2. See http://basic4ppc.com:51042/json/index.html
3.
B4X:
Dim parser As JSONParser
parser.Initialize(<text>)
Dim root As Map = parser.NextObject
Dim AdminUserWebLink As String = root.Get("AdminUserWebLink")
Dim ECommerceLink As String = root.Get("ECommerceLink")
Dim GateList As List = root.Get("GateList")
For Each colGateList As Map In GateList
Dim Latitude As Int = colGateList.Get("Latitude")
Dim Id As Int = colGateList.Get("Id")
Dim Longitude As Int = colGateList.Get("Longitude")
Dim Url As String = colGateList.Get("Url")
Dim Name As String = colGateList.Get("Name")
Next
Dim AdminGateWebLink As String = root.Get("AdminGateWebLink")
 

Shay

Well-Known Member
Licensed User
Longtime User
I am getting from some server this:
{"TotalResults":1,"ReturnedResults":1,"Results":[false],"Timestamp":"2016-10-16T11:22:17.4991352+03:00","Status":"Success"}

Is this JSON? or can I get each value?
 

DonManfred

Expert
Licensed User
Longtime User
Is this JSON?
Yes

go to http://basic4ppc.com:51042/json/index.html
Copy the json into the editfield and press the PARSE button

B4X:
Dim parser As JSONParser
parser.Initialize(<text>)
Dim root As Map = parser.NextObject
Dim ReturnedResults As Int = root.Get("ReturnedResults")
Dim Status As String = root.Get("Status")
Dim Results As List = root.Get("Results")
For Each colResults As String In Results
Next
Dim TotalResults As Int = root.Get("TotalResults")
Dim Timestamp As String = root.Get("Timestamp")

Edit: Yes or no :D I´m looking at the json tree output and now i think the results array is not ok.

Just test it by yourself ;)
if
B4X:
For Each colResults As String In Results
    log(colResults)
Next
prints one "false" then it it ok ;)
 
Last edited:

sanjibnanda

Active Member
Licensed User
Longtime User
hi,

how i can parse this code i got from server

{"category":[{"id":"23","category_name":"Sports","category_image":"sports.jpeg","subcat_count":"1"},{"id":"24","category_name":"General Knowledge","category_image":"gk.jpeg","subcat_count":"1"},{"id":"25","category_name":"Computer","category_image":"computer.png","subcat_count":"0"},{"id":"26","category_name":"physics","category_image":"header.png","subcat_count":"1"},{"id":"27","category_name":"chemistry","category_image":"india 3.png","subcat_count":"0"}],"success":1}
 

DonManfred

Expert
Licensed User
Longtime User
how i can parse this code i got from server
See Post #87 (the one before yours)

B4X:
Dim parser As JSONParser
parser.Initialize(<text>)
Dim root As Map = parser.NextObject
Dim success As Int = root.Get("success")
Dim category As List = root.Get("category")
For Each colcategory As Map In category
Dim category_image As String = colcategory.Get("category_image")
Dim category_name As String = colcategory.Get("category_name")
Dim subcat_count As String = colcategory.Get("subcat_count")
Dim id As String = colcategory.Get("id")
Next
 

sanjibnanda

Active Member
Licensed User
Longtime User
See Post #87 (the one before yours)

B4X:
Dim parser As JSONParser
parser.Initialize(<text>)
Dim root As Map = parser.NextObject
Dim success As Int = root.Get("success")
Dim category As List = root.Get("category")
For Each colcategory As Map In category
Dim category_image As String = colcategory.Get("category_image")
Dim category_name As String = colcategory.Get("category_name")
Dim subcat_count As String = colcategory.Get("subcat_count")
Dim id As String = colcategory.Get("id")
Next

great, you saved my day
 

Shay

Well-Known Member
Licensed User
Longtime User
Yes

go to http://basic4ppc.com:51042/json/index.html
Copy the json into the editfield and press the PARSE button

B4X:
Dim parser As JSONParser
parser.Initialize(<text>)
Dim root As Map = parser.NextObject
Dim ReturnedResults As Int = root.Get("ReturnedResults")
Dim Status As String = root.Get("Status")
Dim Results As List = root.Get("Results")
For Each colResults As String In Results
Next
Dim TotalResults As Int = root.Get("TotalResults")
Dim Timestamp As String = root.Get("Timestamp")

Edit: Yes or no :D I´m looking at the json tree output and now i think the results array is not ok.

Just test it by yourself ;)
if
B4X:
For Each colResults As String In Results
    log(colResults)
Next
prints one "false" then it it ok ;)

Great this is ok..
 
Status
Not open for further replies.
Top