JSON data parsing (GO)

Source: Internet
Author: User
Tags tojson

The previous essay details three kinds of parsing server-side XML data format, and for the server side, the data returned to the client format is generally divided into HTML, XML and JSON of the three formats, then this essay will explain the JSON this point of knowledge, This includes how to parse our JSON data through the two JSON parsing libraries of Json-lib and Gson, and how to parse the JSON data from the server side in our Android client and update it into the UI.

First, what is JSON

JSON (Javascript Object Notation) is a lightweight data interchange format, as compared to XML, because parsing XML is more complex and requires writing large pieces of code, Therefore, the data Interchange format of client and server is often exchanged through JSON. Especially for web development, the JSON data format can be parsed directly by JavaScript on the client.

JSON has two data structures, one is an unordered Jsonobject object in the form of (Key/value), and an object begins with "{" (the left curly brace) and "}" (the closing curly brace) ends. Each "name" is followed by a ":" (colon); "' Name/value ' pair ' is separated by", "(comma).

For example: {"name": "Xiaoluo"}, this is the simplest JSON object, for this data format, the key value must be a string type, and for value, it can be a string, number, object, array and other data types:

Another data format is the set of ordered values, which is known as Jsonarray, an ordered collection of value (s). An array begins with "[" (the left square bracket), and "]" (the right square bracket) ends. Use "," (comma) to separate values.

More about JSON data format can participate in JSON's official website, http://www.json.org/json-zh.html

Second, parsing JSON data format

Two JSON parsing libraries are used to parse our JSON data format and to generate our JSON data format.

1.json-lib (http://json-lib.sourceforge.net/)

Using Json-lib to parse, we need to introduce a third-party package, because Json-lib is divided into two versions, A version is for jdk1.3, a version is for jdk1.5, here we download jdk1.5 Json-lib package, which also need to introduce a few other jar packages:

Once you have downloaded these jar packs, add them to the classpath. Let's take a look at the API that Json-lib gives us.

The two classes we use most commonly are the two classes of Jsonobject and Jsonarray, which represent both JSON objects and JSON arrays, and all two classes implement the JSON interface. Let's take a few small examples to see how we can convert several of our common data formats into our JSON objects (which we generally call JSON data serialization) and then convert the JSON objects into our data format (called deserialization).

① simple serialization and deserialization of JavaBean

public class person{    private int id;    private String name;    Private String address;    Public person ()    {    } 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;    }    Public String getaddress ()    {        return address;    }    public void setaddress (String address)    {        this.address = address;    }    public person (int ID, string name, string address)    {        super ();        This.id = ID;        this.name = name;        this.address = address;    }    @Override public    String toString ()    {        return ' person [id= + ID + ', name= ' + name + ', address= "+ address< c41/>+ "]";    }}

First we define a simple JavaBean object, then convert a person object to a JSON object, and then deserialize the JSON object into our person object.

We first define a Jsontools class, which has two static methods, which we can use to get a JSON-type string object, and a JSON object

public class jsontools{    /**     * Gets a JSON-type string Object     * @param key     * @param value     * @return    */ public static string Getjsonstring (string key, Object value)    {        Jsonobject jsonobject = new Jsonobject ();        Both put and element are placed into the Jsonobject object Key/value pairs//        jsonobject.put (key, value);        Jsonobject.element (key, value);        return jsonobject.tostring ();    }        /**     * Get a JSON object     * @param key     * @param value     * @return */public    static Jsonobject Getjsonobject (String key, Object value)    {        Jsonobject jsonobject = new Jsonobject ();        Jsonobject.put (key, value);        return jsonobject;    }    }

We can directly pass jsonobject jsonobject = new Jsonobject (); This method can be used to get a JSON object and then add the Key/value pair to our JSON object through the element () or the put () method. Let's take a look at the first example to implement a simple person object and the transformation of a JSON object

person person = new person (1, "Xiaoluo", "Guangzhou");    converts a person object to a JSON-type string object        personstring = jsontools.getjsonstring ("person", person);        System.out.println (Personstring.tostring ());

Let's look at the output of the console:

{"Person": {"Address": "Guangzhou", "id": 1, "name": "Xiaoluo"}}

The entire outer brace is a JSON object with a pair of key/value inside of {"Address": "Guangzhou", "id": 1, "name": "Xiaoluo"} is the JSON string object we converted to

Take a look at how to convert a JSON object into our Bean object

Jsonobject jsonobject = jsontools.getjsonobject ("person", person);        The    jsonobject Tobean method allows you to convert a JSON object to a JavaBean        jsonobject personobject = jsonobject.getjsonobject ("person ");        Person Person2 = (person) jsonobject.tobean (Personobject, person.class);        System.out.println (Person2);
person [id=1, Name=xiaoluo, address= Guangzhou]

② converting objects of type list<person>

@Test public    void Testpersonsjson ()    {        list<person> persons = new arraylist<person> ();        person person = new person (1, "Xiaoluo", "Guangzhou");        Person Person2 = new Person (2, "Android", "Shanghai");        Persons.add (person);        Persons.add (Person2);        String personsstring = jsontools.getjsonstring ("Persons", persons);        System.out.println (personsstring);                Jsonobject jsonobject = jsontools.getjsonobject ("Persons", persons);    list<person> is equivalent to a Jsonarray object        jsonarray Personsarray = (jsonarray) Jsonobject.getjsonarray (" Persons ");        list<person> persons2 = (list<person>) personsarray.tocollection (Personsarray, person.class);        System.out.println (PERSONS2);    }
{"Persons": [{"Address": "Guangzhou", "id": 1, "name": "Xiaoluo"},{"Address": "Shanghai", "id": 2, "name": "Android"}]} [Person [Id=1, Name=xiaoluo, address= Guangzhou], person [id=2, name=android, address= Shanghai]

③list<map<string, JSON object conversion of the string>> type

 @Test public void Testmapjson () {list<map<string, string>> List = new ARRAYLIST<MAP&L T        String, string>> ();        map<string, string> map1 = new hashmap<string, string> ();        Map1.put ("id", "001");        Map1.put ("name", "Xiaoluo");        Map1.put ("Age", "20");        map<string, string> map2 = new hashmap<string, string> ();        Map2.put ("id", "002");        Map2.put ("name", "Android");        Map2.put ("Age", "33");        List.add (MAP1);        List.add (MAP2);        String liststring = jsontools.getjsonstring ("list", list);                System.out.println (liststring);        Jsonobject jsonobject = jsontools.getjsonobject ("list", list);        Jsonarray Listarray = Jsonobject.getjsonarray ("list"); list<map<string, string>> list2 = (list<map<string, string>>) listarray.tocollection (        Listarray, Map.class);    System.out.println (LIST2); }
{"List": [{"id": "001", "Age": "\", "Name": "Xiaoluo"},{"id": "002", "Age": "$", "name": "Android"}]} [{id=001, Name=xiaoluo, age=20}, {id=002, name=android, age=33}]

From the example above, we can learn how to transform the data of JavaBean, List, map and JSON data by json-lib this analytic library.

2.gson (http://code.google.com/p/google-gson/)

Let's take a look at the JSON parsing library provided by Google, and we also need to download the Gson jar package and import it into our project Gson.

With Gson, we can easily transform the data objects and JSON objects, where we use two methods, one is Fromjson (), we convert the JSON object to the data object we need, and the other is Tojson (), This is the conversion of our data objects into JSON objects. Let's look at a comprehensive example of how Gson is used:

public class jsonservice{Public person Getperson () {Person person = new person (1, "Xiaoluo", "Guangzhou");    return person;        } public list<person> Getpersons () {list<person> persons = new arraylist<person> ();        person person = new person (1, "Xiaoluo", "Guangzhou");        Person Person2 = new Person (2, "Android", "Shanghai");        Persons.add (person);        Persons.add (Person2);    return persons;        } public list<string> getString () {list<string> List = new arraylist<string> ();        List.add ("Guangzhou");        List.add ("Shanghai");        List.add ("Beijing");    return list; } public list<map<string, String>> getmaplist () {list<map<string, string>> List        = new arraylist<map<string, string>> ();        map<string, string> map1 = new hashmap<string, string> ();        Map1.put ("id", "001");        Map1.put ("name", "Xiaoluo"); Map1.put ("Age", "20");        map<string, string> map2 = new hashmap<string, string> ();        Map2.put ("id", "002");        Map2.put ("name", "Android");        Map2.put ("Age", "33");        List.add (MAP1);        List.add (MAP2);    return list; }}
public static void Main (string[] args) {Gson Gson = new Gson ();        Jsonservice jsonservice = new Jsonservice ();        Person person = Jsonservice.getperson ();        System.out.println ("Person:" + gson.tojson (person)); For the object type, use the Fromjson (String, Class) method to convert the JSON object to a Java object person2 = Gson.fromjson (Gson.tojson (person),        Person.class);        System.out.println (Person2);                System.out.println ("------------------------------------------------");        list<person> persons = Jsonservice.getpersons ();        System.out.println ("Persons:" + Gson.tojson (persons)); /* For generic objects, use the Fromjson (String, Type) method to convert the JSON object to the corresponding generic object * New Typetoken<> () {}.gettype () method * /list<person> persons2 = Gson.fromjson (Gson.tojson (persons), new Typetoken<list<person>> () {}.get        Type ());        System.out.println (PERSONS2); System.out.println ("------------------------------------------------");        list<string> list = jsonservice.getstring ();        System.out.println ("String---->" + gson.tojson (list));        List<string> List2 = Gson.fromjson (Gson.tojson (list), new typetoken<list<string>> () {}.getType ());        System.out.println ("list2---->" + list2);                System.out.println ("------------------------------------------------");        list<map<string, string>> listmap = Jsonservice.getmaplist ();        System.out.println ("Map---->" + Gson.tojson (listmap)); list<map<string, string>> listMap2 = Gson.fromjson (Gson.tojson (Listmap), new Typetoken<list<map        <string, string>>> () {}.gettype ());        System.out.println ("listMap2---->" + LISTMAP2);    System.out.println ("------------------------------------------------"); }

Look at the console output:

Person: {"id": 1, "name": "Xiaoluo", "Address": "Guangzhou"}person [Id=1, Name=xiaoluo, address= Guangzhou]--------------------------- ---------------------persons: [{"id": 1, "name": "Xiaoluo", "Address": "Guangzhou"},{"id": 2, "name": "Android", "Address": "Shanghai" }][person [Id=1, Name=xiaoluo, address= Guangzhou], person [id=2, name=android, address= Shanghai]]--------------------------------- ---------------String---->["Guangzhou", "Shanghai", "Beijing"]list2---->[Guangzhou, Shanghai, Beijing]------------------------------------------ ------MAP---->[{"id": "001", "Age": "A", "name": "Xiaoluo"},{"id": "002", "Age": "$", "name": "Android"}] LISTMAP2---->[{id=001, age=20, Name=xiaoluo}, {id=002, age=33, name=android}]----------------------------------- -------------

Third, the Android client to resolve the server-side JSON data

Let's complete a comprehensive example where the Android client requests some data from the server through a Asynctask asynchronous task and then, after parsing the data, updates the resulting data into our spinner UI control.

Let's start by looking at the server-side code:

@WebServlet ("/cityservlet") public class Cityservlet extends httpservlet{private static final long Serialversionuid = 1    L    Public Cityservlet () {super (); } protected void Doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IO    Exception {this.dopost (request, response); } protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, I        oexception {response.setcontenttype ("text/html;charset=utf-8");        Request.setcharacterencoding ("Utf-8");        Response.setcharacterencoding ("Utf-8");                PrintWriter writer = Response.getwriter ();        String type = Request.getparameter ("type");            if ("JSON". Equals (Type)) {list<string> cities = new arraylist<string> ();            Cities.add ("Guangzhou");            Cities.add ("Shanghai");            Cities.add ("Beijing");            Cities.add ("Hunan"); Map<strinG, list<string>> map = new hashmap<string, list<string>> ();            Map.put ("Cities", cities);            String citiesstring = json.tojsonstring (map);        Writer.println (citiesstring);        } writer.flush ();    Writer.close (); }}

If the parameter requested by the client is Type=json, a JSON data format is responded to the client

Then look at the client's code, first look at the client's layout file, is actually a button and a spinner control, when the button is clicked, the server-side data is requested via the HTTP protocol, and then the data of our spinner control is updated after receiving it.

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" match_parent "> <Text View android:id= "@+id/textview1" android:layout_width= "wrap_content" android:layout_height= "Wrap_cont Ent "android:layout_alignparentleft=" true "android:layout_alignparenttop=" true "Android:layout_margin left= "64DP" android:layout_margintop= "64DP" android:textsize= "20sp" android:text= "City"/> &L T Spinner android:id= "@+id/spinner" android:layout_width= "wrap_content" android:layout_height= "Wrap_co        Ntent "android:layout_aligntop=" @id/textview1 "android:layout_torightof=" @id/textview1 "/> <Button        Android:id= "@+id/button" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android:layout_alignleft= "@+id/textview1"Android:layout_below=" @+id/spinner "android:layout_marginleft=" 22DP "android:layout_margintop=" 130d P "android:text=" Load Data "/></relativelayout>

Write a class in the Android client that parses the JSON data format:

public class jsonutils{    /**     * @param citiesstring    JSON string data obtained from the server     @return    parse JSON string data. Put in List     *    /public static list<string> parsecities (String citiesstring)    {        list<string > cities = new arraylist<string> ();                Try        {            Jsonobject jsonobject = new Jsonobject (citiesstring);            Jsonarray Jsonarray = Jsonobject.getjsonarray ("Cities");            for (int i = 0; i < jsonarray.length (); i++)            {                Cities.add (jsonarray.getstring (i));            }        }        catch (Exception e)        {            e.printstacktrace ();        }                return cities;}    }

Of course our Httputils class is also indispensable:

 public class httputils{/** * @param path Request Server URL address * @param encode encoded format * @return return server-side        Convert data to String */public static string Sendpostmessage (string path, string encode) {string result = "";        HttpClient HttpClient = new Defaulthttpclient ();            try {httppost httppost = new HttpPost (path);            HttpResponse HttpResponse = Httpclient.execute (HttpPost); if (Httpresponse.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK) {httpentity httpentity = h                Ttpresponse.getentity ();                if (httpentity! = null) {result = Entityutils.tostring (httpentity, encode);        }}} catch (Exception e) {e.printstacktrace ();        } finally {Httpclient.getconnectionmanager (). Shutdown ();    } return result; }}

Finally, take a look at our Mainactivity class:

public class Mainactivity extends activity{private Spinner Spinner;    Private button button;    Private arrayadapter<string> adapter;    Private ProgressDialog Dialog;    Private final String City_path_json = "Http://";        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                Setcontentview (R.layout.activity_main);        Spinner = (spinner) Findviewbyid (R.id.spinner);        Button = (button) Findviewbyid (R.id.button);        dialog = new ProgressDialog (mainactivity.this);            Button.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v)                {Dialog.settitle ("hint message");                Dialog.setmessage ("Loading ...");                Dialog.setprogressstyle (Progressdialog.style_spinner);                                Dialog.setcancelable (FALSE); New Myasynctask (). Execute (City_path_json);    }        }); } public class Myasynctask extends Asynctask<string, Void, list<string>> {@Override prote        CTED void OnPreExecute () {dialog.show (); } @Override protected list<string> doinbackground (String ... params) {list<string            > cities = new arraylist<string> ();            String citiesstring = Httputils.sendpostmessage (Params[0], "utf-8");        Parse the server-side JSON data cities = jsonutils.parsecities (citiesstring); return cities; } @Override protected void OnPostExecute (list<string> result) {adapter = new Arraya Dapter<string> (Mainactivity.this, Android.            R.layout.simple_spinner_item, result); Adapter.setdropdownviewresource (Android.            R.layout.simple_spinner_dropdown_item);            Spinner.setadapter (adapter);        Dialog.dismiss ();   }} @Override public boolean Oncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.main, menu);    return true; }}

Of course not. Open our network license

<uses-permission android:name= "Android.permission.INTERNET"/>

Finally, let's take a look at:

This allows us to complete the exchange of data via JSON between the client and server side.

Summary: This essay focuses on the concept of a lightweight data interchange format such as JSON, and explains two parsing classes (Json-lib and Gson) that parse JSON data. Finally, a small example is implemented to exchange data using JSON as a data format on the Android client and server side.

JSON data parsing (GO)

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.