The use of Jsonobject and Jsonarray

Source: Internet
Author: User

Jsonobject and Jsonarray

In the recent learning process, a slightly more complex JSON data is needed to parse the JSON data, and here is a partial example.

1.JSONObject Introduction

The Jsonobject-lib package is a Beans,collections,maps,java arrays and XML and JSON transforms each other's packages.

2. Download the jar Package

Http://files.cnblogs.com/java-pan/lib.rar

* or directly configured in MAVEN's Pom.xml file as follows:

<dependency>            <groupId>net.sf.json-lib</groupId>            <artifactid>json-lib</ artifactid>            <version>2.4</version>            <classifier>jdk15</classifier></ Dependency>

JSON data:

{    "Cartypes":[        {"id": 1, "Imgurl": "Img/l.jpg", "bigimg": "Img/d.jpg", "title": "Bekewilland", "Marketprice": "¥15.29", "Periods": "12 Issue",           "Endrepayone": "96800", "Endrepaytwo": "96800", "Endrepaythree": "93000",           "Endmonthone": "3408", "Endmonthtwo": "3408", "Endmonththree": "3278",           "Repayfirst": "15290", "Repaytwo": "22935", "Repaythree": "30580",           "Monthrepayone": "3578", "Monthrepaytwo": "2878", "Monthrepaythree": "2478",           "Cardetails":
[{ "imageId00": "Img/first-bkwl.jpg", "IMAGEID01": "Img/bkwl01.jpg", "IMAGEID02": "Img/bkwl02.jpg", "ImageId03": "Img/bkwl03.jpg", "ImageId04": "Img/bkwl04.jpg", "Carname": "Buick", "Carmatter": "Weilang", "Carvolume": "1.5L", "Sitnum": "5", "Cargearbox": "6 block hand from one", "Caremission": "Guo V", "Carldone": "One-piece cockpit", "Carldtwo": "Suede Interior", "Carldthree": "Panorama Skylight", "Carldfour": "exhibition wing type HID Headlight" }] }, {"id": 2, "Imgurl": "Img/l.jpg", "bigimg": "Img/d.jpg", "title": "Infiniti", "Marketprice": "¥18.98", "Periods": "12 Issue", "Endrepayone": "126800", "Endrepaytwo": "126800", "Endrepaythree": "126800", "Endmonthone": "4458", "Endmonthtwo": "4458", "Endmonththree": "4458", "Repayfirst": "18980", "Repaytwo": "28470", "Repaythree": "37960", "Monthrepayone": "2738", "Monthrepaytwo": "1878", "Monthrepaythree": "998", "Cardetails":
[{
"imageId00": "Img/first.jpg", "IMAGEID01": "Img/yfnd01.jpg", "IMAGEID02": "Img/yfnd02.jpg", "ImageId03": "Img/yfnd03.jpg", "ImageId04": "Img/yfnd04.jpg", "Carname": "Infiniti", "Carmatter": "ESQ", "Carvolume": "1.6L", "Sitnum": "5", "Cargearbox": "CVT stepless speed Change", "Caremission": "Guo V", "Carldone": "Custom Wheels", "Carldtwo": "Multifunction steering wheel", "Carldthree": "LED Tail light", "Carldfour": "Leather Seat" }]
}
]}

When the JSON data is received above, to get to the inside of the key corresponding to the value of what should be done, such as to get the value of the title, get the value of IMAGEID02 in Cardetails, etc.


In the face of such an array and object nested in the case of the need to split the data, the main idea or the key value, for the array type or the need to first remove the element according to the subscript. Jsonobject and Jsonarray need to be used here as well.

Simplifying the JSON data above is: (Keep an ID here for easy identification)

{    "cartypes": [              {                 "id": 1, "bigimg": "Img/dt-bkwl.jpg",                 "cardetails": [{ "IMAGEID02": "Img/bkwl02.jpg}"               }

{
"id": 2, "bigimg": "Img/xxx.jpg",
"Cardetails": [{"imageId002": "Img/xx.jpg"}]
} ]}   

This is the simplified JSON data, it can be seen that the string outermost is a large key Cartypes object, and its value is a JSON array in the form of more complex JSON data. Continue to analyze the [] section, you can see that there are two elements of the array, each element is {} Wrapped JSON object, their elements are the same, and then see each element contains several key-value pairs of data, where the value of the key cardetails is a nested JSON array, It contains a JSON object. The analysis is complete. How can we (get the data) parse it?

Using Jsonobject and Jsonarray

There are two ways to take data in general, and you need to choose.

Mode ①:

obtained directly by jsonobject.getstring ("key"), this method can only get one at a time.

Way ②

Gets by building the bean corresponding to the JSON object.

I used the above example in two ways, because of the need to use the id,bigimg and cardetails in the majority of the data, so I use the cardetails encapsulated as a bean, easy to use, and the other used less, so directly based on the key to get the value.

It is also important to note that the Jsonobject,jsonarray, respectively, correspond to the two formats of the JSON data. That is {"Zhang San": "Male"}, [{Zhang San ":" Man "}], you need to convert it to the corresponding object when used.

As (example):

Jsonobject Jsonobject = Jsonobject.fromobject (JSON);   // To convert a JSON string to Jsonobject Jsonarray Jsonarray = Jsonarray.fromobject (JSON);  // To convert a JSON string to Jsonarray

There is a point to point out: In the key value is always required according to the value of the key, from the outside to the inside, take the inner layer of the key value needs to get the value of the outer key first, if the cross-value will be an error.

The following shows the values:

Jsonobject Jsonobject = Jsonobject.fromobject (JSON);   // Convert a JSON string to Jsonobject String cartypes=jsonobject.getstring ("Cartypes");      // Remove the information from the GetString ("Cartypes") Jsonarray Jsonarray = Jsonarray.fromobject (cartypes);  // converts the Cartypes (a set of) value strings that are taken to Jsonarray
String title = job.getstring ("id"); //Fetch String bigimg = job.getstring ("bigimg"); // Big Picture
System. out.println ("bigimg:" +bigimg);       You can show the values that you've got bigimg 

Since the basic of cardetails is the required value, one value is troublesome, so the cardetails is encapsulated into a bean as follows:

Cardetails.java

 Public classCardetails {PrivateString imageId00; PrivateString imageId01; PrivateString imageId02; PrivateString imageId03; PrivateString imageId04; PrivateString Carname; PrivateString Carmatter; PrivateString Carvolume; Private intSitnum; PrivateString Cargearbox; PrivateString caremission; PrivateString Carldone; PrivateString Carldtwo; PrivateString Carldthree; PrivateString Carldfour; //The get Set method and the ToString method are slightly}

Here, you need to turn the keys in Cardetails into the properties in Cardetails as follows:

// encapsulating Cardetail as a bean
Jsonarray Cardetailarr=job.getjsonarray ("Cardetails"); // Convert a JSON string to Jsonarray Jsonobject cardetailobj = cardetailarr.getjsonobject (0); // gets the first element of the array Cardetails cardetails = (cardetails) Jsonobject.tobean (Cardetailobj, cardetails. Class); // Encapsulation into Beans
System. out.println ("cardetails:" +cardetails); Can get to the data 


Finally, we enclose some code:

 Publicvoid Geticardetail (intID) {String JSON=NULL; Try{JSON=icardetail.geticardetail (ID); }Catch(Exception e) {e.printstacktrace (); }        intJsonid=0;//the ID value in the JSON arrayJsonobject Jsonobject = Jsonobject.fromobject (JSON);//Convert a JSON string to JsonobjectString cartypes=jsonobject.getstring ("Cartypes");//Remove the information from the GetString ("Cartypes")Jsonarray Jsonarray = Jsonarray.fromobject (cartypes);//converts the Cartypes (a set of) value strings that are taken to Jsonarray//traversing the Jsonarray array        if(Jsonarray.size () >0){             for(intI=0;i<jsonarray.size (); i++) {Jsonobject job= Jsonarray.getjsonobject (i);//turn each object into a JSON objectJsonid= (int) Job.get ("id");//get the ID value in each object                if(jsonid==ID) {                    //Get Correlation valueString title = job.getstring ("title");                              String bigimg = job.getstring ("bigimg");                      String Repayfirst = job.getstring ("Repayfirst");                    String Endrepayone = job.getstring ("Endrepayone");                    String Endmonthone = job.getstring ("Endmonthone"); String Marketprice = job.getstring ("Marketprice");//encapsulating Cardetail as a beanJsonarray Cardetailarr=job.getjsonarray ("Cardetails");//Convert a JSON string to JsonarrayJsonobject cardetailobj = cardetailarr.getjsonobject (0);//gets the first element of the arrayCardetails cardetails = (cardetails) Jsonobject.tobean (Cardetailobj, Cardetails.class);//Encapsulation into Beans//Output DisplaySystem.out.println ("******************"); System.out.println ("Jsonid:" +Jsonid); System.out.println ("Title:" +title); System.out.println ("Bigimg:" +bigimg); System.out.println ("Repayfirst:" +Repayfirst); System.out.println ("Endrepayone:" +Endrepayone); System.out.println ("Endmonthone:" +Endmonthone); System.out.println ("Marketprice:" +Marketprice); System.out.println ("Cardetails:" +cardetails);
}

The use of Jsonobject and Jsonarray

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.