Generation and parsing of basic JSON strings under Android

Source: Internet
Author: User

JSON strings have been used before, but in the Java environment, now moved to the Android environment, Java inside the generated parsing JSON string of the jar and Android in the conflict, so it can only be used with Android.

  Previously checked the information on the Internet, feeling a lot of talk is very messy, give examples directly, and do not explain even if the completion of their own affirmation is clear, but let the reader must be a bit difficult to understand. And there are many methods of parsing, and here, I will introduce one of the most primitive and simple. I hope my poor expressive power will not affect your understanding.   First let's talk about JSON string format   Object Pet (PET)  class pet{ int petid;//number  string petname;//name  string pettype;//type  }  The JSON string form of the object is  {"pet": [{"Petid": +, "petname": "Name1", "PetType": "Type1"}]}   If we create multiple pet objects, the string is:  {"pet": [{"Petid": "PetName": "Name1", "PetType": "Type1"},{"Petid": 1002, "PetName": "Name2", "PetType": "type2"}]}  is defined here if it is of type int, the value is not added "number, if string type or other type, then add".  , generating JSON strings   Well, let's use Android's jsonobject to create a JSON string.   [java] <span style= "font-size:18px" >public String Pettojson (Pet Pet) {         String jsonresult = "";//define return string          Jsonobject object = new Jsonobject ();//Create A total object, this object to the entire JSON string          try {             Jsonarray JSON Array = new Jsonarray ();//json array containing the contents of PAll ET objects              Jsonobject jsonobj = new Jsonobject ();//pet object, JSON form              jsonobj.put ("Petid", Pet.getpetid ());//Add value to Pet object          & nbsp   Jsonobj.put ("PetName", Pet.getpetname ());              jsonobj.put ("PetType", Pet.getpettype ());             //Add each data as an object to the array              Jsonar Ray.put (jsonobj);//Add Pet objects to the JSON array              Object.put ("Pet", jsonarray);// Add an array containing pet to the total object                          Jsonresult = OB Ject.tostring ();//Generate return string         } catch (Jsonexception e) {            //TODO auto-generated catch block              e.printstacktrace ();        }          Logi ("generated JSON string:" +jsonresult);          return jsonresult;     }</span>    The final result is: {"pet": [{"Petid": +, "petname": "Name1", "PetType": "Type1"}] }  of course, if we want to generate multiple objects, then we just need to call a few more times  [java] <span style= "font-size:18px" >jsonarray.put (jsonobj);// Adding a Pet object to the JSON array </span>   This method is possible. In addition to the outermost object we can understand this, in fact, we generate a type of  object{ List<pet> list; } , It's just the outermost object we can't see. Second, parsing JSON string   in fact, parsing and generation is relative, how to generate, then it should be how to return to the resolution   incoming json={"pet": [{"Petid": "," PetName ":" Name1 "," PetType " : "Type1"}]} [java]  <span style= "font-size:18px" >public Pet Jsontopet (String json) {         if (Json.startswith ("error")) {//Here you can do a check, if it is not in JSON format, return directly              return null;         }          Pet pet=new Pet ()///Ready to return pet object    &nbsp     try {             Jsonobject jsonobject=new jsonobject (JSON);//We need to put the JSON String as a large object              Jsonarray Jsonarray=jsonobject.getjsonarray ("Pet");// This gets the array loaded with all the pet objects              Jsonobject jsonpet = jsonarray.getjsonobject (0);// Gets the first pet object in this array                            Stri Ng petid=jsonpet.getstring ("Petid");//Get the parameters of the pet object              String petname= Jsonpet.getstring ("PetName");              String pettype=jsonpet.getstring ("PetType");                            Pet.setpetid (Petid); Add the parameters to the pet object.              Pet.setpetid (petname);              Pet.setpetid (PetType);         } catch (Jsonexception e) {             E.printstacktrace ();         }          Logi ("JSON to Pet:" +pet.tostring ());//Print out Pet object parameters.          return pet;     }</span>    Three, summing up actually the parsing of JSON string is very simple, of course, in this article I give a simple example. The JSON strings that are passed in in real-world applications are not standard. It is possible that: [{"Petid": +, "petname": "Name1", "PetType": "Type1"}] such, so obviously this is an array form, then we will use  [java]  < Span style= "font-size:18px" >jsonarray jsonarray=new </span><span style= "font-size:18px" >JSONArray </span><span style= "font-size:18px" > (JSON);</span>   to parse is OK.   Of course there are many kinds of specific forms, but we can only distinguish between the object and the group of the concept of mutual inclusion, it will be able to parse out.   Reprint: http://www.2cto.com/kf/201309/244866.html

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.