Android App-Google's official JSON analysis tool Gson use

Source: Internet
Author: User

One, Gson basic introduction

Gson(also known asGoogleGson) isGoogleThe company publishes an open sourceJavaLibrary. The main purpose isSerialization of Javaobject isJsonstring, or anti-Serialization JSONstring intoJavaObject.

That is, the Java object and the JSON string are converted to each other. Analytical.


Second, usage

Gson's application is mainly for the Tojson and Fromjson two conversion functions, and before using such an object to transform the type of object to be created and the success of its members the JSON string is successfully converted into the corresponding object. The corresponding JavaBean is created first. The fields in the JavaBean are the same as the JSON to be converted. Otherwise, there will be a case of parsing failure.


Parse JSON into a JavaBean object:

JavaBean

public class Person {private string name;private int age;private string Gender;public string GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;} Public String Getgender () {return gender;} public void Setgender (String gender) {This.gender = Gender;<pre name= "code" class= "Java" >
}}
JSON string:
{"Name": "Zhangsan", "age": +, "gender": "Male"}

Parse this JSON string into a Java object:

Person person = new Gson (). Fromjson (JSON, person.class);
This makes it possible to parse the JSON string into a JavaBean object.
Inserts a little, a conversion between the JSON string and the Jsonobject object. Because some places may need JSON strings, some places need to be jsonobject objects
The JSON string is converted intoJsonobjectObject:
Jsonobject jsonobject = new Jsonobject (JSON);
Jsonobject object to JSON string
String jsonstring = json.tostring ();


The above situation is just one of the simplest examples. If the JSON string is slightly more complex, it involves nesting the object to see the following example:
{    "Status_code": "0",    "result": {        "card_edate": "1451491200",        "Edate_remark": "Get free before December 31, 2015", "        Card_remark": "1, members enjoy a variety of value-added privileges \r\n2, member exclusive pre-save 500",        "merchant_id": "2",        "card_img": "/http Www.yuelife.com/srdz_pic/baralogo.jpg ",        " card_id ":" 2 "    },    " Status_desc ":" OK "}
This is a JSON string returned by the server, where the object is nested, and the result parameter inside the JSON string is also an object. The way such a situation is handled is as follows:
Jsonobject jsonobject = json.optjsonobject ("result");
This will then get a Jsonobject object and then be able to use this Jsonobject object to get the JavaBean object or directly parse. Suppose you want to get the JavaBean object. Directly with Fromjson, assuming that you want to parse a number of the parameters in the result, do the following, for example:
String Cardnumber = jsonobject.optstring ("card_id");
This will give you a Cardnumber value.


The above scenario is nesting of objects. Another case is nesting of arrays, see the following example:

{"Status_code": "0", "result": [{"Rows": [{"Branch_longitud E ":" 113.9760310000 "," Branch_userid ":" 273 "," branch_addr ":" Yi Tian Holiday Plaza, no. No. 9028 Shennan Avenue, Nanshan District, Shenzhen L 3 layers "," branch_status ":" 1 "," Is_default ":" 1 "," Branch_phone ":" 13 316467909,18875900656 "," Branch_creattime ":" 0 "," City ":" Shenzhen ","                    Branch_park ":" In front of the parking space "," province ":" Guangdong "," Branch_guidelines ":" 11 Road Bus ",                    "Branch_updatetime": "0", "merchant_id": "2", "Branch_precision": "", "Branch_latitude": "22.5375870000", "branch_id": "" "," Branch_name ":"                Cosmopolitan Panyu Store "}]," shop_city ":" Shenzhen "}, {" Rows ": [                    {"Branch_longitude": "113.3802380000", "Branch_userid": "273", "branch_addr": "Guangzhou city, Guangdong Province"                    Fanyu District nan Cun zhen Panyu Avenue (formerly Yingbin Road) A2 Building, 1-2 Floor "," Branch_status ":" 1 "," Is_default ":" 0 ", "Branch_phone": "13711112346,02038823585", "Branch_creattime": "0", "City": "Guang State City "," Branch_park ":" in front of parking space "," province ":" Guangdong "," Branch_guideline S ":" 120-way Bus "," branch_updatetime ":" 0 "," merchant_id ":" 2 "," Bra                    Nch_precision ":", "Branch_latitude": "23.0032640000", "branch_id": "26", "Branch_name": "Cosmopolitan Fanyu District nan Cun zhen Panyu Store"}], "shop_city": "Guangzhou"}], "s Tatus_desc ":" OK "}
This JSON is slightly more complex than the JSON object returned by the server. Nesting of objects and arrays is involved.

The value of the result field is an array with objects and arrays nested inside the array. In this case, the solution is actually very easy, that is, the contents of [] are treated as a collection. Treats the contents of {} as objects
So this JSON parsing, first look at the result of the [] content. is made up of two {} objects, so the following paragraph is defined as a javabean. and parse it into objects.

{"Rows": [                    {"Branch_longitude": "113.9760310000", "Branch_userid": "273", "Branch_addr": "L3, Yi Tian Holiday Plaza, no. No. 9028 Shennan Avenue, Nanshan District, Shenzhen", "Branch_status": "1", "Is_                    Default ":" 1 "," Branch_phone ":" 13316467909,18875900656 "," Branch_creattime ":" 0 ",                    "City": "Shenzhen", "Branch_park": "Parking spaces in front of the door", "Province": "Guangdong", "Branch_guidelines": "11 Road Bus", "branch_updatetime": "0", "merchant_id": " 2 "," Branch_precision ":" "," Branch_latitude ":" 22.5375870000 ","         branch_id ":", "Branch_name": "Cosmopolitan Panyu Shop"}], "shop_city": "Shenzhen" }
The JavaBean defined are as follows:
public class Orderseatrows {private list<orderstorebean> rows;private String shop_city;public list< Orderstorebean> getRows () {return Rows;} public void Setrows (list<orderstorebean> rows) {rows = rows;} Public String getshop_city () {return shop_city;} public void setshop_city (String shop_city) {this.shop_city = shop_city;}}
Because the Rows field in the JavaBean is also made up of [], that is, rows is also an array, so. Use rows as a collection of {} contents. That is, the following is also defined as a javabean, parsed into an object
public class Orderstorebean {private string Branch_addr;private string Branch_userid;private string branch_id;private String Branch_name;private string Province;private string city;private string Branch_status;private string Branch_ Latitude;private string Branch_longitude;private string is_default;private string Branch_phone;private string Branch_ Creattime;private string Branch_park;private string Branch_guidelines;private string Branch_updatetime;private string Merchant_id;private string Branch_precision;public string getbranch_addr () {return branch_addr;} public void Setbranch_addr (String branch_addr) {this.branch_addr = branch_addr;} Public String Getbranch_userid () {return branch_userid;} public void Setbranch_userid (String branch_userid) {this.branch_userid = Branch_userid;} Public String getbranch_id () {return branch_id;} public void setbranch_id (String branch_id) {this.branch_id = branch_id;} Public String Getbranch_name () {return branch_name;} public void Setbranch_name (String branch_Name) {this.branch_name = Branch_name;} Public String getprovince () {return province;} public void Setprovince (String province) {this.province = province;} Public String getcity () {return city;} public void Setcity (String city) {this.city = city;} Public String Getbranch_status () {return branch_status;} public void Setbranch_status (String branch_status) {this.branch_status = Branch_status;} Public String Getbranch_latitude () {return branch_latitude;} public void Setbranch_latitude (String branch_latitude) {this.branch_latitude = Branch_latitude;} Public String Getbranch_longitude () {return branch_longitude;} public void Setbranch_longitude (String branch_longitude) {this.branch_longitude = Branch_longitude;} Public String Getis_default () {return is_default;} public void Setis_default (String is_default) {this.is_default = Is_default;} Public String Getbranch_phone () {return branch_phone;} public void Setbranch_phone (String branch_phone) {this.branch_phone = Branch_phone;} Public String Getbranch_creattiMe () {return branch_creattime;} public void Setbranch_creattime (String branch_creattime) {this.branch_creattime = Branch_creattime;} Public String Getbranch_park () {return branch_park;} public void Setbranch_park (String branch_park) {this.branch_park = Branch_park;} Public String Getbranch_guidelines () {return branch_guidelines;} public void Setbranch_guidelines (String branch_guidelines) {this.branch_guidelines = Branch_guidelines;} Public String Getbranch_updatetime () {return branch_updatetime;} public void Setbranch_updatetime (String branch_updatetime) {this.branch_updatetime = Branch_updatetime;} Public String getmerchant_id () {return merchant_id;} public void setmerchant_id (String merchant_id) {this.merchant_id = merchant_id;} Public String getbranch_precision () {return branch_precision;} public void Setbranch_precision (String branch_precision) {this.branch_precision = branch_precision;}}
Once the above class is defined, it is possible to parse the contents of the first parsing [], that is, the method of parsing the array Gson parse the array first, such as the following: OptJSONArray9 () method Jo returns the Jsonobject object to the server
Jsonarray Orderjsonarray = Jo.optjsonarray ("result");
After the above analysis, we get a Jsonarray object, this object can be based on the actual situation, continue to parse.

if (null! = orderjsonarray&& orderjsonarray.length () > 0) {for (int i = 0; i < orderjsonarray.length (); i++) {Jsonobject Cityjsonobject = Orderjsonarray.getjsonobject (i); Orderseatrows Orderrow = Gsonutils.toobject ( Cityjsonobject.tostring (), orderseatrows.class);
Facilitates Jsonarray objects. Use the Getjsonobject () method. will be able to getThe Jsonobject object is obtained from all Jsonobject objects in Jsonarray . will be able to parse the JSON into a previously defined object.
Summary:several data models commonly used in the development. are introduced in the above, in fact, only to grasp a principle, see [] analytic array. See {} parsed into an object. Then the complex JSON data can be very easy to parse out the data we want. Prepare data for later development.






Copyright notice: This article blog original article. Blogs, without consent, may not be reproduced.

Android App-Google's official JSON analysis tool Gson use

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.