Android: Parsing JSON data

Source: Internet
Author: User

JSON (JavaScript Object Notation) is a lightweight data interchange format, and the data that is returned when the server is accessed is often HTML, XML, and JSON, which we need to parse. JSON has two structures, one is an object, and the other is an array. The former data format is {Key:value,key:value,...} The latter data format is: ["Java", "JavaScript", "VB",...], of course, the array can also be an object.

Example one: Using the SDK's class library to parse JSON data, one of the most important classes is Jsonreader, whose construction method is public jsonreader (Reader in); The more important method is Beginarray (), BeginObject () , Hasnext (), nextstring (), Nextint (), and the last end and close methods. Feel a bit like sax and pull parsing XML, but also step by step parsing down.

Create a new tool class:

<span style= "FONT-SIZE:14PX;" >package Com.example.jsondemo;import Java.io.ioexception;import Java.io.stringreader;import Android.util.jsonreader;public class Jsonutils {public static void Parsejson (String jsondata) {Jsonreader reader = new Jso   Nreader (new StringReader (Jsondata));                Instantiate a Jsonreader object try {reader.beginarray ();       Begins parsing an array while (Reader.hasnext ()) {//Returns True Reader.beginobject () if the current array or object exists element;   Begins parsing the object while (Reader.hasnext ()) {String tagName = Reader.nextname (); Prints the parsed data out if (tagname.equals ("name")) {System.out.println ("-->>" + reader.nextstring ())}, or else if (t Agname.equals ("Age")) {System.out.println ("-->>" + reader.nextint ());}}         Reader.endobject ();                  Parse the end of an object} reader.endarray (); Parse out array reader.close ();} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} </span> 
<span style= "FONT-SIZE:14PX;" >package Com.example.jsondemo;import Android.os.bundle;import Android.support.v7.app.actionbaractivity;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;public class MainActivity Extends Actionbaractivity {//[{\ "name\": \ "leelit\", \ "age\": 20},{\ "name\": \ "Lina\", \ "age\": +}]   The JSON data returned by the emulation server is private String jsondata = "[{\" name\ ": \" leelit\ ", \" age\ ": 20},{\" name\ ": \" Lina\ ", \" age\ ": +}]";  Here/is the escape character @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Button button = (button) Findviewbyid (R.id.button); Button.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO auto-generated method StubSystem.out.println ("Begin to parse Json"); Jsonutils.parsejson (Jsondata);}});}} </span>
Results:


Parsing process: [{' Name ': ' Leelit ', ' age ': 20},{' name ': ' Lina ', ' age ': 21}]. Begin parsing the array → Parse the first object →tagname = "Name", print out leelit→ The first object also has elements, return true →tagname = "Age", print out 20→ parse the first object, and a second object, return to True, and start Parses the second object, and so on.


Example two: Using Gson to parse JSON data containing an object is to convert the JSON data into Java objects. First download a Gson class library Click to open the link, and then import it into the project: the jar file into the Libs folder, then right-click Bulid path, the last add path can use this Gson class library.

Create a new user class:

Package Com.example.jsondemo;public class User {private string name;private int age;public String getName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;}}
Create a new tool class:

<span style= "FONT-SIZE:14PX;" >package Com.example.jsondemo;import Java.io.stringreader;import Com.google.gson.gson;import Android.util.jsonreader;public class Jsonutils {public static void Parsejson (String jsondata) {Gson Gson = new Gson (); 
   
    //instantiates a Gson object user user = Gson.fromjson (jsondata, user.class);    Gson the JSON data into a JavaBean object. System.out.println ("-->>" + user.getname () + "" + user.getage ());}   } </span>
   
<span style= "FONT-SIZE:14PX;" >package Com.example.jsondemo;import Android.os.bundle;import Android.support.v7.app.actionbaractivity;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;public class MainActivity Extends Actionbaractivity {//{"name": "Leelit", "Age": $;p rivate String jsondata = "{\" name\ ": \" leelit\ ", \" age\ ": 20}" ; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); Button button = (button) Findviewbyid (R.id.button); Button.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO auto-generated method StubSystem.out.println ("Begin to parse Json"); Jsonutils.parsejson (Jsondata);}});}} </span>
Results:


Example three: Using Gson to parse the array JSON data

Create a new user class

Create a new tool class

Package Com.example.jsondemo;import Java.lang.reflect.type;import Java.util.iterator;import java.util.LinkedList; Import Com.google.gson.gson;import Com.google.gson.reflect.typetoken;public class Jsonutils {public static void Parsejson (String jsondata) {Type ListType = new typetoken<linkedlist<user>> () {}.gettype (); Gson Gson = new Gson (); linkedlist<user> users = Gson.fromjson (Jsondata, listtype);    Convert JSON data to a LinkedList object for (User user:users) {System.out.println ("-->>" + user.getname () + "" + user.getage () );}}}
Package Com.example.jsondemo;import Android.os.bundle;import Android.support.v7.app.actionbaractivity;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;public class MainActivity Extends Actionbaractivity {//[{\ "name\": \ "leelit\", \ "age\": 20},{\ "name\": \ "Lina\", \ "age\": 21}]private String Jsondata = "[{\" name\ ": \" leelit\ ", \" age\ ": 20},{\" name\ ": \" Lina\ ", \" age\ ": +}]"; @Overrideprotected void OnCreate ( Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Button button = (button) Findviewbyid (R.id.button); Button.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO auto-generated method StubSystem.out.println ("Begin to parse Json"); Jsonutils.parsejson (Jsondata);}});}}
Results:


Summary: Be familiar with Jsonreader and Gson this two class is possible. Watch the video tutorial a lot of the server is done by themselves, and then return to the data to resolve their own, this should be more profound, but now not the server this piece. Also know a method is to use Fastjson to parse, this temporarily do not learn first.


Android: Parsing JSON data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.