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

joesmithjunior

Member
Licensed User
Longtime User
Json

Can someone point me in a direction of a tutorial that will help me parse this JSON string

[{"uid":"3","0":"3","uname":"joesmith","1":"joesmith","uemail":"joesmith@gmail.com","2":"joesmith@gmail.com","utype":"1","3":"1","ufullname":"Joseph Smith","4":"Joseph Smith","ucomname":"My Hosting Pro","5":"My Hosting Pro","uadd":"1558 E 3rd St.","6":"1558 E 3rd St.","ucity":"Omaha","7":"Omaha","ustate":"NE","8":"NE","uzip":"68114","9":"68114","umobilenum":"4026201422","10":"4026201422","uphonenum":"402-620-1422","11":"402-620-1422","ufaxnum":"","12":"","uimage":"","13":"","uaddedon":"2012-04-27","14":"2012-04-27"}]

I've gone through this tutorial and I'm just not getting it. I need to parse this string and place different parts on it in labels or text boxes.
 
Last edited:

Erel

B4X founder
Staff member
Licensed User
Longtime User
Here:
B4X:
Sub Activity_Create(FirstTime As Boolean)
   Dim p As JSONParser
   p.Initialize(File.ReadString(File.DirAssets, "1.txt"))
   Dim list1 As List
   list1 = p.NextArray
   Dim map1 As Map
   map1 = list1.Get(0)
   Log(map1)
   Dim umobilenum As String
   umobilenum = map1.Get("umobilenum")
End Sub
 

joesmithjunior

Member
Licensed User
Longtime User
Perfect. Worked great. One last question. What function do I need to look into to pull a json string out of a larger string. The JSON string I gave you is at the beginning of a web page I download. If I use the whole string it says it is not a valid JSON string so I need to use a function to pull the json string out of the entire string I store in a variable.
 

Inman

Well-Known Member
Licensed User
Longtime User
The code Erel posted above works for the innermost array in the json code. The issue is json is a complex nested structure. There are objects, which contain arrays, which again contain other objects, like that it can go on. To use Erel's code, you need to traverse the tree from top and reach the innermost object/array which has the string. For that you need a visual representation of the json data. I use the following web page:

JSON 2 HTML

Paste the sample json string Erel gave in the first post and hit json 2 html button. You will get a visual representation of the whole data which will show which object contains what array and so on. Now compare the visual data and the B4A code Erel used to traverse the whole thing. That is how I learnt this stuff yesterday.
 

joesmithjunior

Member
Licensed User
Longtime User
Thanks Inman. That helps a lot. Also I figured out how to pull the entire JSON object out of the webpage by using indexof and substring2 . Thanks for all the help!
 

kikloo

Member
Licensed User
Longtime User
Hi,

Question: I am getting 2 fields in my json data namely: id and name.
In listview I am showing name. How do I add id with name so that id is kept hidden from user and only name is visible ?

Thanks.
 

Erel

B4X founder
Staff member
Licensed User
Longtime User

Nyptop

Active Member
Licensed User
Longtime User
I have been trying to parse the following JSON for I while but I'm getting confused with the loops.

Can anybody point me in the right direction for parsing this is B4A?
B4X:
[
    {
        "category": "burglary", 
        "month": "2012-04", 
        "location": {
            "latitude": "52.6391872", 
            "street": {
                "id": 883491, 
                "name": "On or near Mantle Road"
            }, 
            "longitude": "-1.1507308"
        }, 
        "context": "", 
        "id": 8816657, 
        "location_type": "Force",
        "outcome_status": {
            "category": "Under investigation", 
            "date": "2012-04"
        }
    },
 

Nyptop

Active Member
Licensed User
Longtime User
Thanks for the help. My code goes as follows:

B4X:
   Dim List1 As List
   Dim JSON As JSONParser
   JSON.Initialize(File.ReadString(File.DirInternalCache, jsonfile &".json"))
   List1.Initialize
   List1 = JSON.NextArray
   Dim m As Map 'helper map for navigating
   m = List1.Get(0)
   Dim loc As Map
   loc = m.Get("location")
      For i = 0 To m.Size - 1
      Dim Longitude(i) As Double
      Dim Latitude(i) As Double
      Longitude(i) = loc.Get ("longitude")
      Latitude(i) = loc.Get ("latitude")
      Dim Markers(i) As Marker
      Markers(i).Initialize("", "", Latitude(i), Longitude(i), Null)
      Next
   Dim Markerss As List
   Markerss.Initialize2(Array As Object(Markers(i))) 
   MarkersOverlay1.AddMarkers(Markerss)

I'm still having issues though. The problem is as follows: 'LastException java.lang.ArrayOutOfBounds'

What would you suggest my problem is?
 
Last edited:

Nyptop

Active Member
Licensed User
Longtime User
I forgot to add that the problem occurs on the line 'Longitude(i) = loc.Get ("longitude")'.

What is my problem?

Cheers,

Neil
 
Last edited:

Nyptop

Active Member
Licensed User
Longtime User
I have updated the code. I think I am much closer.What exactly am I doing wrong?
 

Nyptop

Active Member
Licensed User
Longtime User
Thanks for the reply Erel,

What I am trying to get from the JSON is all of the latitudes and the longitudes and then plot those onto a mapview using markers.

I'm afraid I have become really stuck with all the loops. I really don't know how to get the 'location' object (from the JSON) as many times as the API (Street-level crimes - Police API) makes one and then how to make a number of doubles (as in variables) to store the latitudes and the longitudes so that I can add a number of markers?

This is where I have gotten to without loops (and it works):

B4X:
Dim List1 As List
   Dim JSON As JSONParser
   JSON.Initialize(File.ReadString(File.DirInternalCache, jsonfile &".json"))
   List1.Initialize
   List1 = JSON.NextArray
         Dim M As Map 'helper map for navigating
   M = List1.Get(0)
         Dim loc As Map
   loc = M.Get("location")
      For i = 0 To loc.Size - 1
      Dim Longitude As Double
      Dim Latitude As Double
      Longitude = loc.Get ("longitude")
      Latitude = loc.Get ("latitude")
      Dim Markers As Marker
      Markers.Initialize("", "", Latitude, Longitude, Null)
      Next
      Dim Markerss As List
   Markerss.Initialize2(Array As Object(Markers)) 
   MarkersOverlay1.AddMarkers(Markerss)

Could you point me in the direction of a loops tutorial perhaps?

Thanks for all the help,

Neil
 

Nyptop

Active Member
Licensed User
Longtime User
Could you give me an example of some code that could do this? I'm very grateful for the excellent help here at B4A and I have recommended it to my friends :)
 
Status
Not open for further replies.
Top