Android parsing JSON data

Source: Internet
Author: User

1.JSON (JavaScript Object Notation) is a lightweight data interchange format. It is based on a subset of JavaScript (standard ECMA-262 3rd edition-december 1999). JSON takes a completely language-independent text format, but also uses a similar idiom to the C language family (c, C + +, C #, Java, JavaScript, Perl, Python, etc.). These features make JSON an ideal data exchange language. Easy to read and write, but also easy to machine parse and generate (network transfer speed).

Data format for 2.json

1>object

{

"Name" AAAAAAAAA: "Jackson",

"Age": 100

 }

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/6C/47/wKioL1VEfuvCrs63AACLVIGXepU096.jpg "title=" Qq20150502153151.png "alt=" Wkiol1vefuvcrs63aaclvigxepu096.jpg "/>

2> Array

{

"Students":

[

{"Name": "Jackson", "Age": 100},

{"Name": "Yu", "Age": 22}

]

}

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/6C/47/wKioL1VEf5fRyhhAAAB_US2ItPE665.jpg "title=" Qq20150502153448.png "alt=" Wkiol1vef5fryhhaaab_us2itpe665.jpg "/>

Example: The server-side data generated by the return of JSON data format, the Android client to obtain JSON data, parse the JSON format of data.

1. Using JSON requires a few packages, download the next package placed in the server project engineering

Json-lib-2.3-jdk15.jar Commons-beanutils-1.7.0.jar Commons-httpclient-3.1.jar Commons-lang-2.3.jar Commons-logging-1.0.4.jar Commons-collections-3.1.jar ezmorph-1.0.3.jar2. Create a new project under MyEclipse, first create a new JSON tool class, and by invoking the tool class, you can convert the data into a JSON-formatted
public class Jsontools {public Jsontools () {//TODO auto-generated Constructor stub}/** * @param key * denotes JSON characters String header information * @param object * is the type of the parsed collection * @return */public static string createjsonstring (string key, Object value) {Jsonobject jsonobject = new Jsonobject (); Jsonobject.put (key, value); return jsonobject.tostring ();}

3. Assigning values to Objects

package com.json.service;import java.util.arraylist;import java.util.hashmap;import  Java.util.list;import java.util.map;import com.json.domain.person;public class jsonservice  {public jsonservice ()  {}    /*     * {" Person ": {" Address ":" Beijing "," id ": 1001," name ":" Jack "}}      */public person  getperson ()  {person person = new person (1001,  "Yu",  "Beijing"); return  person;}     /*     * {"Persons": [{"Address": "Guangxi", "id": 1001, " Name ":" Jack "},{" Address ":" Guangdong "," id ": 1002," name ":" Rose "}]}      */public  list<person> getlistperson ()  {List<Person> list = new  Arraylist<person> (); Person person1 = new person (1001,  "Yu",  "Guangxi"); person person2  = new person (1002,  "Rose",  "Guangdong"); List.add (Person1); List.add (Person2);return  List;}    /*    * {"liststring": ["Beijing", "Shanghai", "Hunan"]}      */public list<string> getliststring ()  {list<string> list  = new ArrayList<String> (); List.add ("Beijing"); List.add ("Shanghai"); List.add ("Hunan"); Return list;}     //{"Listmap": [{"id": 1001, "Address": "Beijing", "name": "Jack"},{"id": 1002, "Address": " Shanghai "," name ":" Rose "}]} public list<map<string, object>> getlistmaps ()  {list<map<string, object>> list = new arraylist<map<string,  Object>> (); Map<string, object> map1 = new hashmap<string, object> (); Map1.put (" ID ",  1001); Map1.put (" Name ", " Jack ") Map1.put (" Address ", " Beijing "); Map<string, object> map2 = new hashmap<string, object> (); Map2.put ("id",  1002 ); Map2.put ("name",  "Rose"), Map2.put ("Address",  "Shanghai"); List.add (MAP1); List.add (MAP2); return  list;}}

4. Create a new servlet call method that generates JSON, and then output the generated JSON-formatted data to the client

Public void dopost (Httpservletrequest request, httpservletresponse response) throws  servletexception, ioexception {response.setcontenttype ("Text/html;charset=utf-8"); Request.setcharacterencoding ("Utf-8"); Response.setcharacterencoding ("Utf-8"); Printwriter out = response.getwriter (); string jsonstring =  ""; String action_flag =request.getparameter ("Action_flag");if  (action_flag.equals ("person"))   {jsonstring = jsontools.createjsonstring ("person",  service.getperson ()); System.out.println ("person");}  else if  (Action_flag.equals ("persons")  {jsonString =  Jsontools.createjsonstring ("Persons",  service.getlistperson ()); System.out.println ("Persons");}  else if  (Action_flag.equals ("liststring")  {jsonString =  Jsontools.createjsonstring ("ListString",  service.getliststring ()); System.out.println ("liststring");}  else if  (Action_flag.equals ("Listmap"))  {jsonstring = jsontools.createjsonstring ("Listmap",  Service.getlistmaps ()); System.out.println ("Listmap");} Out.println (jsonstring); Out.flush (); Out.close ();}

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/6C/50/wKiom1VFzP_RsZWVAAFQfyUpEzc040.jpg "title=" Qq20150503152308.png "alt=" Wkiom1vfzp_rszwvaafqfyupezc040.jpg "/>


5. Build Android client, create a new HttpClient tool class, get the server-side JSON format data

Package com.android.myjson.http;import java.io.bytearrayoutputstream;import java.io.ioexception ;import java.io.inputstream;import java.net.httpurlconnection;import java.net.url;public  Class httputils {public httputils ()  {// todo auto-generated constructor  stub}public static string getjsoncontent (String url_path)  {try {URL  Url = new url (Url_path); httpurlconnection connection =  (HttpURLConnection)  url.openconnection (); Connection.setconnecttimeout (+); Connection.setrequestmethod ("GET"); Connection.setdoinput (True);int  Code = connection.getresponsecode ();if  (code == 200)  {return  Changeinputstream (Connection.getinputstream ());}}  catch  (exception e)  {// TODO: handle exception}return  "";} Private static string changeinputstream (Inputstream inputstream) {// TODO Auto-generated method stubString jsonString =  ""; Bytearrayoutputstream outputstream = new bytearrayoutputstream ();int len =  0;byte[] data = new byte[1024];try {while  ((Len = inputstream.read ( Data)  != -1)  {outputstream.write (Data, 0, len);} Jsonstring = new string (Outputstream.tobytearray ());}  catch  (ioexception e)  {// TODO Auto-generated catch  Blocke.printstacktrace ();} return jsonstring;}}

6. Create a new JSON tool class to parse JSON data

Package com.android.myjson.json;import java.util.arraylist;import java.util.hashmap;import  java.util.Iterator;import java.util.List;import java.util.Map;import org.json.JSONArray; Import org.json.jsonobject;import com.android.myjson.domain.person;public class jsontools  {public jsontools ()  {// TODO Auto-generated constructor stub}public  Static person getperson (string key, string jsonstring)  {Person person  = new person ();         //{"person": {"Address": "Beijing", "id" : 1001, "name": "Jack"}}try {jsonobject jsonobject = new jsonobject (jsonstring); Jsonobject personobject = jsonobject.getjsonobject ("person");p Erson.setid (PersonObject.getInt (" ID "));p Erson.setname (personobject.getstring (" name "));p erson.setaddress (personobject.getstring (" Address "));}  catch  (EXCEPTION&Nbsp;e)  {// todo: handle exception}return person;} Public static list<person> getpersons (string key, string jsonstring)   {list<person> list = new arraylist<person> ();         //{"Persons": [{"Address": "Guangxi", "id": 1001, "name": "Jack"},{"Address": "Guangdong", "id": 1002 , "name": "Rose"}]}try {            jsonobject  jsonobject = new jsonobject (jsonstring);             jsonarray jsonarray = jsonobject.getjsonarray (Key);             for  (int i = 0; i <  jsonarray.length ();  i++)  {                 jsonobject jsonobject2&nBsp;= jsonarray.getjsonobject (i);                 person person = new person ();                 person.setid (Jsonobject2.getint ("id"));                 person.setname ( Jsonobject2.getstring ("name"));                 person.setaddress (jsonobject2.getstring ("Address"));                 list.add (person);             }        } catch  ( Exception e)  {            // todo:  handle exception&nbSp;       }        return list ;} Public static list<string> getlist (string key, string jsonstring)  { List<string> list = new arraylist<string> ();try {jsonobject  Jsonobject = new jsonobject (jsonstring); Jsonarray jsonarray = jsonobject.getjsonarray (Key);for  (int i = 0; i  < jsonarray.length ();  i++)  {string msg = jsonarray.getstring (i); List.add (msg);}}  catch  (Exception e)  {// todo: handle exception}return list;} Public static list<map<string, object>> listkeymaps (String key,String  jsonstring)  {list<map<string, object>> list = new arraylist <Map<String, Object>> (TRY&NBSP;{JSONOBJECT&NBSP;JSONOBJECT&NBSP);; = new jsonobject (jsonstring); Jsonarray jsonarray = jsonobject.getjsonarray (Key);for  (int i = 0; i  < jsonarray.length ();  i++)  {JSONObject jsonObject2 =  Jsonarray.getjsonobject (i); Map<string, object> map = new hashmap<string, object> ();Iterator< String> iterator = jsonobject2.keys ();while  (Iterator.hasnext ())  {String json _key = iterator.next (); Object json_value = jsonobject2.get (Json_key);if  (json_ Value == null)  {json_value =  "";} Map.put (Json_key, json_value);} List.add (map);}}  catch  (Exception e)  {// todo: handle exception}return list;}}

7. Print out the parsed data

String Path = "Http://192.168.191.1:8080/jsonProject/servlet/JsonAction?action_flag=person"; String jsonstring = httputils.getjsoncontent (path); Person person = Jsontools.getperson ("person", jsonstring); LOG.I (TAG, person.tostring ());


Android parsing JSON data

Related Article

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.