Android Series---Example of JSON data parsing _android

Source: Internet
Author: User
Tags data structures serialization tojson

The essay details the three kinds of XML data format, which is sent to the server side, and the data format returned to the client is generally divided into HTML, XML and JSON, then this essay will explain the knowledge of JSON. 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 on our Android client and update to the UI.

One, what is JSON

JSON (Javascript Object notation) is a lightweight data interchange format that, in contrast to the XML data Interchange format, because parsing XML is more complex and requires writing large sections of code, So the data interchange format between client and server is often exchanged via JSON. In particular, for web development, JSON data formats can be parsed directly from the client via JavaScript.

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

For example: {"name": "Xiaoluo"}, this is the simplest JSON object, for which the key value must be of type string, 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 are called Jsonarray, and arrays are ordered collections of value. An array begins with "[" (left bracket), and "]" (right bracket) ends. Values are separated by the "," (comma) value.
More about JSON data formats can participate in the JSON website, http://www.json.org/json-zh.html

II. parsing JSON data formats

Here we will use two JSON parsing libraries to parse our JSON data format and 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 the Json-lib is divided into two versions, One version is for jdk1.3, and one version is for jdk1.5, and here we download the jdk1.5 Json-lib package, which also needs to introduce several other jar packages:
After downloading these jar packs, add them to the classpath. Let's look at the API Json-lib gives us.

Our two most commonly used classes are the two classes Jsonobject and Jsonarray, representing both the JSON object and the JSON array, all of which have the JSON interface implemented, Here are a few small examples to see how we can convert several of our common data formats into our JSON objects (which we typically call JSON data serialization) and then convert the JSON object into our data format (called deserialization).

① simple JavaBean serialization and deserialization

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< c43/>+ "]";
  }



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

Let's start by defining a Jsontools class, which has two static methods that 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 ();
    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 go directly through jsonobject jsonobject = new Jsonobject (); This method can get a JSON object and then add a Key/value pair to our JSON object via element () or put () method. Let's take a look at the first example to implement a simple conversion of the person object and the JSON object

person person = new person (1, "Xiaoluo", "Guangzhou");  converts a person object to a JSON-type string Object string
    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 which {"Address": "Guangzhou", "id": 1, "name": "Xiaoluo"} is the JSON string object we converted to

Let's take a look at how to convert a JSON object into our Bean object

Jsonobject jsonobject = jsontools.getjsonobject ("person", person);  the Tobean method of Jsonobject enables you to convert a JSON object into 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]

② convert list<person> type of object

@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> corresponds 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, string>> type of JSON object conversion

 @Test public void Testmapjson () {list<map<string, string>> List = n
    EW 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);
    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 ': ' A ', ' name ': ' Android '}]}
[{id=001, Name=xiaoluo, age=20}, {id=002, name=android, age=33}]

Through the above example, we can understand how to json-lib this parsing library to achieve JavaBean, List, map and other data and JSON data conversion

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

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

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

public class Jsonservice {public Person Getperson () {The person person = The 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); For type object, use the Fromjson (String, Class) method to convert the JSON object to the Java object person Person2 = Gson.fromjson (Gson.tojson (person), Perso
    N.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 * * Lis t<person> persons2 = Gson.fromjson (Gson.tojson (persons), new Typetoken<list<person>> () {}.gettype (
    ));
    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 output of the console:

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": "M", "name": "Xiaoluo"},{"id": "002", "Age": "A", "name": "Android"}]
LISTMAP2---->[{id=001, age=20, Name=xiaoluo}, {id=002, age=33, name=android}]
------------------------------------------------

Iii. Resolving server-side JSON data on the Android client

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

Let's look at the server-side code first:

@WebServlet ("/cityservlet") public class Cityservlet extends HttpServlet {private static final long Serialversionuid =

  1L;
  Public Cityservlet () {super (); } protected void Doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexcep
  tion {this.dopost (request, response); } protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexce
    ption {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 client requests a parameter that 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, in fact, is a button and a spinner control, when clicked button, through the HTTP protocol to request server-side data, and then after receiving the update of our spinner control data

<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 "> <TextV Iew android:id= "@+id/textview1" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" a Ndroid:layout_alignparentleft= "true" android:layout_alignparenttop= "true" android:layout_marginleft= "64DP" and roid:layout_margintop= "64DP" android:textsize= "20sp" android:text= "City"/> <spinner android:id= "@+i D/spinner "android:layout_width=" wrap_content "android:layout_height=" wrap_content "android:layout_alignTop=" @ Id/textview1 "android:layout_torightof=" @id/textview1 "/> <button android:id=" @+id/button "Android:lay Out_width= "Wrap_content" android:layout_height= "wrap_content" android:layout_alignleft= "@+id/textView1" Androi d:layout_below= "@+id/spinner" Android:layout_marginleft= "22DP" android:layout_margintop= "130DP" android:text= "Load data"/> </RelativeLayout>

 

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

public class Jsonutils
{
  /**
   * @param citiesstring  JSON string data obtained from the server side
   * @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 not less:

public class Httputils
{
  /**
   * @param path  request Server URL address
   * @param encode  encoded format
   * @return  converts server-side returned 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 = Httpresponse.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://172.25.152.34:8080/httptest/CityServlet?type=json";
    @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) {di
        Alog.settitle ("hint Information");
        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 protected 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 server-side JSON data cities = jsonutils.parsecities (citiesstring); return cities; } @Override protected void OnPostExecute (list<string> result) {adapter = new Arrayadapter<stri Ng> (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. Turn on our network authorization

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

Finally, let's look at the effect chart:

This completes the client-server exchange of data via JSON.

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

Original link: http://www.cnblogs.com/xiaoluo501395377/p/3446605.html
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.