Android JSON parsing data

Source: Internet
Author: User

A: Introduction to JSON

JSON refers to JavaScript Object notation, a lightweight text data interchange format, similar to XML, but smaller, faster, and easier to parse than XML

Two: The comparison between JSON and XML (copy online)

Advantages:

simpler than XML format;
JSON is a better format for exchanging data; XML is a better format for exchanging documents;
JSON is easier to machine read, using a simple client library or self-support (JavaScript);
JSON can be supported by the browser client;
can support a variety of common data structures, records, lists, trees;
21 languages supported to parse and generate JSON formats
Disadvantages:

There is no CDATA-like feature in XML that is not suitable for passing binary data such as sounds and pictures;
JSON does not have the ability to display, compared with XML;
JSON is not extensible, as compared to XML.

Three: JSON is used to describe data structures in two ways

1, a collection of "name/value" pairs, also known as JSON Object, separated by ":" Before the name and value

{Name:value}

For example:

{"width": "123", "Height": "456"}

2, an ordered list of values, also known as a JSON Array

For example:

{"Employee": [{"width": "123", "Height": "345"}, {"width": "234", "height": "455"}, {"width": "566", "height": "269"}]}

IV: The JAR package required for JSON parsing data

Five: JSON data parsing

When parsing JSON data, distinguish between parsing a JSON Object or a JSON Array, and then parsing

(1) parsing one of the JSON object

Example: parsing {"name": "Value"}

The value of the string name in the JSON object can be obtained by jsonobject.getstring ("name") method

Create Jsonobject, convert the jsonstring string to the text corresponding to the JSON object

Jsonobject Demojson = new Jsonobject (jsonstring);

String s = demojson.getstring ("name");//You can get the value corresponding to name

(2) Parsing JSON object Two

One consists of two "name/value"

{"name1": "Android:", "name2": "Java"}

The value of the string name in the JSON object can be obtained by jsonobject.getstring ("name") method

Create Jsonobject, convert the jsonstring string to the text corresponding to the JSON object

Jsonobject Demojson = new Jsonobject (jsonstring);

String name1 = demojson.getstring ("name1");

String name2 = demojson.getstring ("name2");

(3) Parsing JSON Array

Parse json literal {"number": "1,1,3,5"}

Create Jsonarray, convert the jsonstring string to the text corresponding to the JSON object

Jsonobject Demojson = new Jsonobject (jsonstring);

Gets the array of number pairs used

Jsonarray list = Demojson.getjsonarray ("number");

for (int i = 0,k = List.length (); i < K; i + +)

{

Other uses of GetString (i),,, similar

System.out.println (List.getint (i));

}

(4) parsing JSON oject with JSON array mixed object

{"Books": [{"Zhang": "Value1", "Zhang": "Value2"}]}

Jsonobject Demojson = new Jsonobject (jsonstring);

The first is to get the books corresponding value

Jsonarray list = Demojson.getjsonarray ("books");

Then take out the list value in turn

for (int i = 0, k = list.length (); i < K; i++)

{

The value in the first Jsonarray is the JSON Object name/value pair, and then the value is obtained by GetString ("Zhang")

System.out.println (List.getjsonobject (i). GetString ("Zhang");

}

Data inside the server

Package Com.test.demo;import Java.io.ioexception;import Java.io.printwriter;import java.util.arraylist;import Java.util.list;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Net.sf.json.JSONArray Import Net.sf.json.jsonobject;public class Jsondemoservlet extends HttpServlet {private static final long       Serialversionuid = -7368225680407826408l;        Private list<user> List; /** * Processing data submitted by post */@Overrideprotected void DoPost (HttpServletRequest request, httpservletresponse response) THR oWS servletexception, IOException {//TODO auto-generated Method Stubdoget (request, response);} /** * out the data submitted by Get mode */@Overrideprotected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {//TODO auto-generated method Stubresponse.setcontenttype ("Text/plain"); Response.setcharacterencoding ("UTF-8"); PrintWriterout = Response.getwriter ();        Prepare user Data preparedata ();      JSON array Jsonarray array = new Jsonarray ();    for (user bean:list) {//single user json object Jsonobject obj = new Jsonobject ();   try{obj.put ("id", Bean.getid ());   Obj.put ("Name", Bean.getname ());   Obj.put ("Email", bean.getemail ());     Obj.put ("Gender", Bean.getgender ());   }catch (Exception e) {//Todo:handle Exception}//array.put (obj);   Array.add (obj);      }//Output Out.write (array.tostring ());      Out.flush (); Out.close (); } private void Preparedata () {list = new arraylist<user> (); User Bean1 = new user (); Bean1.setid (1001); Bean1.setname ("Tony"); Bean1.setemail ("[email protected]");  Bean1.setgender ("male"); List.add (BEAN1);     User Bean2 = new user (); Bean2.setid (1002); Bean2.setname ("Jack");    Bean2.setemail ("[email protected]");      Bean2.setgender ("male");         List.add (BEAN2);    User Bean3 = new user ();       Bean3.setid (1003);    Bean3.setname ("Marry"); bean3.seTemail ("[email protected]");    Bean3.setgender ("female");        List.add (BEAN3);    User Bean4 = new user ();     Bean4.setid (1004);    Bean4.setname ("Linda");      Bean4.setemail ("[email protected]");     Bean4.setgender ("female");       List.add (BEAN4); }}

The corresponding object text is:

Package Com.test.demo;public class User {private int id;private string Name;private string Email;private string gender;pub Lic String Getemail () {return email;} public void Setemail (String email) {this.email = email;} Public String Getgender () {return gender;} public void Setgender (String gender) {This.gender = gender;} public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;}}

Create TextView on client to display parsed data

Main.xml

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" fill_parent "    android:layout_height=" fill_parent "    android:o rientation= "vertical" >    <textview        android:id= "@+id/textview" android:layout_width= "Fill_        Parent "        android:layout_height=" Wrap_content "/></linearlayout>


Main mainactivity

Package Com.test;import Java.io.bufferedreader;import Java.io.inputstreamreader;import org.apache.http.HttpEntity; Import Org.apache.http.httpresponse;import Org.apache.http.client.httpclient;import Org.apache.http.client.methods.httpget;import Org.apache.http.impl.client.defaulthttpclient;import Org.apache.http.params.httpconnectionparams;import Org.apache.http.params.httpparams;import Org.json.JSONArray; Import Org.json.jsonobject;import android.app.activity;import android.os.bundle;import Android.widget.TextView; public class Mainactivity extends activity {/** Called when the activity is first created. */@Overridepublic void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.main); try {stringbuffer sb = new StringBuffer (); String url = "Http://192.168.1.100:8080/article/JSONDemoServlet"; String BODY = getcontent (URL); Jsonarray array = new Jsonarray (body), for (int i = 0; i < array.length (); i++) {Jsonobject obj = array.getjsonobject (i) ; Sb.apPend ("ID:"). Append (Obj.getint ("id")). Append ("\ t"), Sb.append ("Name:"). Append (obj.getstring ("name")). Append ("\r\ N "), Sb.append (" Gender: "). Append (Obj.getstring (" Gender ")). Append (" \ t "); Sb.append (" Email: "). Append (obj.getstring ("email")). Append ("\ r \ n"); Sb.append ("----------------------\ r \ n");} TextView TextView = (TextView) Findviewbyid (R.id.textview); Textview.settext (sb.tostring ());}  catch (Exception e) {//Todo:handle Exception}}private string getcontent (string url) throws Exception {StringBuilder SB = New StringBuilder (); HttpClient client = new Defaulthttpclient (); Httpparams httpparams = Client.getparams ();//Set Network timeout parameter httpconnectionparams.setconnectiontimeout (HttpParams, 3000); Httpconnectionparams.setsotimeout (Httpparams, 5000); HttpResponse response = Client.execute (new HttpGet (URL)); httpentity entity = response.getentity (), if (entity! = null) {BufferedReader reader = new BufferedReader (New Inputstreamre Ader (Entity.getcontent (), "UTF-8"), 8192); String line = null;while (line = Reader.readlINE ()) = null) {Sb.append (line + "\ n");} Reader.close ();} return sb.tostring ();}}

Android JSON parsing 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.