In Android, gson can be used to parse JSON data
First, download gsonapifrom code.google.com/p/google-gson/downloads/list:
Google-gson-1.7.1-release.zip
Copy the gson-1.7.jar to libs (the project root directory creates a new libs folder.
You can use either of the following methods to parse JSON data:
Parse JSON data by getting the jsonreader object:
String jsondata = "[{\" USERNAME \ ": \" Arthur inking \ ", \" userid \ ": 001 },{ \" USERNAME \ ": \" Jason \", \ "userid \": 002}] "; try {jsonreader reader = new jsonreader (New stringreader (jsondata); reader. beginarray (); While (reader. hasnext () {reader. beginobject (); While (reader. hasnext () {string tagname = reader. nextname (); If (tagname. equals ("username") {system. out. println (reader. nextstring ();} else if (tagname. equals ("userid") {system. out. println (reader. nextstring ();} reader. endobject ();} reader. endarray ();} catch (exception e) {e. printstacktrace ();}
By ing JSON data into an object, you can use the fromjson () method of the gson object to obtain an object array for operations:
Create a pojo object corresponding to the JSON data user. Java: http://www.my400800.cn
Public class user {private string username; private int userid; Public String GetUserName () {return username;} public void setusername (string username) {This. username = username;} public int getuserid () {return userid;} public void setuserid (INT userid) {This. userid = userid ;}}
Use the gson object to obtain user object data for corresponding operations:
Type listtype = new typetoken <shortlist <user >> (){}. getType (); gson = new gson (); writable list <user> Users = gson. fromjson (jsondata, listtype); For (iterator = users. iterator (); iterator. hasnext ();) {user = (User) iterator. next (); system. out. println (user. getUserName (); system. out. println (user. getuserid ());}
If the JSON string to be processed contains only one JSON object, you can directly use fromjson to obtain a user object:
string jsondata = "{\" USERNAME \ ": \" Arthur inking \ ", \" userid \ ": 001}"; gson = new gson (); user user = gson. fromjson (jsondata, user. class); system. out. println (user. getUserName (); system. out. println (user. getuserid ();