Download the free trial version
Basic4android Video
Features
Tutorials and manuals
Showcase
Screenshots

Go Back   Android Development Forum - Basic4android > Basic4android > Basic4android Getting started & Tutorials
Documentation Wiki Register Members List Windows Mobile Search Today's Posts Mark Forums Read

Basic4android Getting started & Tutorials Android development starts here. Please do not post questions in this sub-forum.

Android JSON tutorial

Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 12-16-2010, 09:41 AM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 25,935
Awards Showcase
Basic4ppc Founder 
Total Awards: 1
Default Android JSON tutorial

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:
Code:
{"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).
Code:
    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'.
Code:
m = Map1.Get("menu")
The object that maps to "menu" is assigned to m.
Code:
m = m.Get("popup")
The object that maps to "popup" is now assigned to m.
Code:
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.
Code:
    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:
Code:
    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.

Attached Files
File Type: zip JSONExample.zip (5.2 KB, 1101 views)
Reply With Quote
  #2 (permalink)  
Old 05-05-2012, 08:09 PM
Junior Member
 
Join Date: Apr 2012
Posts: 10
Default 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":"joesmit h","uemail":"joesmith@gmail.com","2":"joesmith@gma il.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":"402 6201422","10":"4026201422","uphonenum":"402-620-1422","11":"402-620-1422","ufaxnum":"","12":"","uimage":"","13":"","ua ddedon":"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 by joesmithjunior : 05-05-2012 at 08:17 PM.
Reply With Quote
  #3 (permalink)  
Old 05-06-2012, 06:57 AM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 25,935
Awards Showcase
Basic4ppc Founder 
Total Awards: 1
Default

Here:
Code:
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
Reply With Quote
  #4 (permalink)  
Old 05-07-2012, 02:21 AM
Junior Member
 
Join Date: Apr 2012
Posts: 10
Default

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.
Reply With Quote
  #5 (permalink)  
Old 05-07-2012, 03:04 AM
Senior Member
 
Join Date: Feb 2011
Posts: 489
Default

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.
Reply With Quote
  #6 (permalink)  
Old 05-07-2012, 03:33 AM
Junior Member
 
Join Date: Apr 2012
Posts: 10
Default

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!
Reply With Quote
  #7 (permalink)  
Old 06-15-2012, 04:17 PM
Knows the basics
 
Join Date: Nov 2011
Posts: 138
Default

So, can anybody let me know how I could interpret a JSON file from the web (this is what I want to interpret Street-level crimes - Police API)

Thanks,

Neil
Reply With Quote
  #8 (permalink)  
Old 06-15-2012, 04:36 PM
Junior Member
 
Join Date: Jun 2012
Posts: 23
Default

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.
Reply With Quote
  #9 (permalink)  
Old 06-17-2012, 07:01 AM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 25,935
Awards Showcase
Basic4ppc Founder 
Total Awards: 1
Default

It is better to start a new thread for this question as it is not really related to the JSON tutorial.

You should define a custom Type that holds the two values and then use ListView.AddSingleLine2 to add the text and the type.
See this link: http://www.basic4ppc.com/forum/basic...cond-line.html
Reply With Quote
  #10 (permalink)  
Old 06-17-2012, 07:40 AM
Junior Member
 
Join Date: Jun 2012
Posts: 23
Default

Quote:
Originally Posted by Erel View Post
It is better to start a new thread for this question as it is not really related to the JSON tutorial.

You should define a custom Type that holds the two values and then use ListView.AddSingleLine2 to add the text and the type.
See this link: http://www.basic4ppc.com/forum/basic...cond-line.html
Hi,

Sorry I forgot to update this, I did that and its working great!

Thanks.
Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are On

Similar Threads
Thread Thread Starter Forum Replies Last Post
Android Serial tutorial Erel Basic4android Getting started & Tutorials 119 03-21-2013 11:18 PM
android NDK support? Cor Bugs & wishlist 10 01-24-2011 03:32 AM
Android me1... linum Chit Chat 4 06-16-2010 07:12 PM
Hallo Android Filippo Chit Chat 0 05-03-2010 06:38 PM
Support for Android epsharp Basic4ppc Wishlist 3 05-14-2009 07:44 PM


All times are GMT. The time now is 11:06 AM.


Powered by vBulletin® Version 3.6.12
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.3.0