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

roarnold

Active Member
Licensed User
Longtime User
1.txt

Where does "1.txt" from the example end up? I changes it to jinfo.txt and I can not find it. I get an error on the "initialize" command that is to create the "jinfo.txt".

When files are created in an app does the file with Dir Assets go to the "Files" folder under the app?

THanks,
R
 

manolis

Member
Licensed User
Longtime User
Shorter Json syntax for data recordsets

The json string has the syntax:

[{field1:value1,field2:value2,…,fieldx:valuex},{field1:value1,field2:value2,…,fieldx:valuex},...].


Is it possible to simplify the string according to the following syntax, in order to have less download data volume?

[{value1,value2,…,valuex},{value1,value2,…,valuex},...]
 

leonardoffsilva

Member
Licensed User
Longtime User
Please, can help me ? I have this result on a JSON consult :

{"result":[[{"Descricao":"PENEIRA ARCO MADEIRA ARROZ 50","Preco":"6"},{"Descricao":"PENEIRA ARCO MADEIRA ARROZ 55","Preco":"6,22"},{"Descricao":"PENEIRA ARCO MADEIRA ARROZ 60","Preco":"8,04"},{"Descricao":"PENEIRA ARCO MADEIRA CAFE 50","Preco":"6"},{"Descricao":"PENEIRA ARCO MADEIRA CAFE 55","Preco":"6,22"},{"Descricao":"PENEIRA ARCO MADEIRA CAFE 60","Preco":"8,04"},{"Descricao":"PENEIRA ARCO MADEIRA FEIJAO 50","Preco":"6"},{"Descricao":"PENEIRA ARCO MADEIRA FEIJAO 55","Preco":"6,22"},{"Descricao":"PENEIRA ARCO MADEIRA FEIJAO 60","Preco":"8,04"},{"Descricao":"PENEIRA ARCO MADEIRA FUBA 30","Preco":"3,9"},{"Descricao":"PENEIRA ARCO MADEIRA FUBA 40","Preco":"6,6"}]]}

how can I get the value of "Descricao" and the value of "Preco"
as string ?

Thank´s a Lot!
 

Azlan

Member
Licensed User
Longtime User
Here is an example of breaking down a JSON string that is from a database table to a list of objects (class).

This example assumes there is a class called ClassEmployee that has the following properties: Name, Age, Address and the database table rows have the same columns.

With that said the code example below uses variables names for that paradigm.

B4X:
Dim EmployeeList : EmployeeList.Initialize


Private Sub GetEmployees(str As String)

  Dim parser As JSONParser : parser.Initialize(str)
  
  Dim Table As List = parser.NextArray ' B4A Vesion 2.20 variable assignment

  EmployeeList.Clear ' Required if this sub called again

  Dim ColName As String = "Value" ' B4A Vesion 2.20 variable assignment
      
  For I = 0 To Table.Size - 1
    
    Dim objEmployee As ClassEmployee : Dim Column As Map : Dim Row As List
  
    Row = Table.Get(I)  ' Gets a Row
  
    ' Get Columns
    Column = Row.Get(0) : objEmployee.Name    = Column.Get(ColName)
    Column = Row.Get(1) : objEmployee.Age     = Column.Get(ColName)
    Column = Row.Get(2) : objEmployee.Address = Column.Get(ColName)

    EmployeeList.Add(objEmployee) 'Add objEmployee to List

  Next

End Sub

Cheers
 
Last edited:

jalle007

Active Member
Licensed User
Longtime User
I need to parse JSON like this:

{"Flight1":[{"what":"Beograd","value":""},{"what":"Broj leta","value":"JU 109, JA 1376"},{"what":"Avio-kompanija","value":"JAT AIRWAYS"},{"what":"Tip aviona","value":"AT72"},{"what":"Planirano vrijeme","value":"06:20"},{"what":"Status leta","value":"Odletio"}],"Flight2":[{"what":"Beograd","value":""},{"what":"Broj leta","value":"SOP 4121"},{"what":"Avio-kompanija","value":"SOLINAIR LTD"},{"what":"Tip aviona","value":"SF34"},{"what":"Planirano vrijeme","value":"16:35"},{"what":"Status leta","value":""}]}

result should contain info about two flights objects Flight1 & Flight2


could you please give me sample how to do it , using Map object maybe ?
 

wimpie3

Well-Known Member
Licensed User
Longtime User
There seems to be a small bug in JSONGenerator.ToString : I see plenty of \n characters in the output stream. A leftover from .ToPrettyString?
 

Jeffrey Cameron

Well-Known Member
Licensed User
Longtime User
Given an unknown JSON response string, is there a simple way to parse it into a tree-node-like structure if you don't know which parse function to use (i.e response could be formatted for NextArray or NextObject and you don't know which it is)?
 

Jeffrey Cameron

Well-Known Member
Licensed User
Longtime User
Thank you, Erel, that was exactly what I was looking for.

I've created and attached an example to parse a supplied JSON string into a simple node structure, hopefully someone else can use it or cannibalize it as a starting point for something they need.

Thanks again for your help!
 

Attachments

  • JsonTree.zip
    10.8 KB · Views: 803

faisal

New Member
I want take the json from server in internet, the json created using php, how can I got the json?
I try using File.ReadString, but it does'nt work, i try using httprequest, but its same, can u give me a example json from server internet ?
thanks
 
Status
Not open for further replies.
Top