Android Application-Use of Google's official Json parsing tool Gson

Source: Internet
Author: User

Android Application-Use of Google's official Json parsing tool Gson

1. Gson Introduction

Gson (also known as Google Gson) is an open-source Java Library released by Google. It mainly uses serialized Java objects as JSON strings or deserialized JSON strings as Java objects. That is, the conversion and parsing between Java objects and json strings.


Ii. Usage

Gson applications mainly include toJson and fromJson conversion functions, before using this type of object conversion, you must create the object type and its members to successfully convert the JSON string to the corresponding object. The corresponding javabean is created first. The fields in the javabean file must correspond to the json file to be converted one by one. Otherwise, the parsing will fail.


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 age) {this. age = age;} public String getGender () {return gender;} public void setGender (String gender) {this. gender = gender;
}}
Json string:
{"Name": "zhangsan", "age": 20, "gender": "male "}

Parse the json string into a java object:

Person person = new Gson().fromJson(json, Person.class);
In this way, the json string can be parsed into a javabean object.
Insert a bit. The conversion between the json string and the JSONObject object. In some cases, the json string may be required. In some cases, the jsonobject object is required.
Convert a json string to a JSONObject:
JSONObject jsonobject = new JSONObject(json);
Convert a JSONObject object to a json string
String jsonString = json.toString();


The above is just a simple example. If the json string is a little more complex and involves object nesting, see the following example:
{"Status_code": "0", "result": {"card_edate": "1451491200", "edate_remark": "Free before January 1, December 31, 2015", "card_remark ": "1. Members enjoy a variety of value-added privileges \ r \ n2, member exclusive deposit 500 to send 50", "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, which involves object nesting. The result parameter in the json string is also an object. The solution is as follows:
JSONObject jsonObject = json.optJSONObject("result");
In this way, a JSONObject object is obtained, and then the javabean object can be obtained through the JSONObject object or parsed directly. To obtain a javabean object, use fromjson directly. to parse a parameter in result, perform the following operations:
String cardNumber = jsonobject.optString("card_id");
In this way, the cardNumber value is obtained.
The above case is the object nesting, and another case is the array nesting. Let's look at the example below:
{"Status_code": "0", "result": [{"Rows": [{"branch_long1_":" 113.9760310000 "," branch_userid ":" 273 ", "branch_addr": "L3, yitian holiday Plaza, 9028 ShenNan Avenue, Nanshan District, Shenzhen", "branch_status": "1", "is_default": "1", "branch_phone ": "13347467909,18875900656", "branch_creattime": "0", "city": "Shenzhen city", "branch_park": "parking space in front of door", "province": "Guangdong ", "branch_guidelines": "11 bus", "branch_updatetime": "0", "merchant_id": "2", "branch_precision": "", "branch_latitude ": "22.5375870000", "branch_id": "25", "branch_name": "Sihai Panyu store"}], "shop_city": "Shenzhen City" },{ "Rows ": [{"branch_long.pdf": "113.3802380000", "branch_userid": "273", "branch_addr": "1-2 floor, building A2, wanbo center, Panyu Avenue, Nancun town, Panyu district, Guangzhou City, Guangdong Province ", "branch_status": "1", "is_default": "0", "branch_phone": "13711108346,02038823585", "branch_creattime": "0", "city": "Guangzhou city ", "branch_park": "parking space in front of the door", "province": "Guangdong", "branch_guidelines": "120 bus", "branch_updatetime": "0", "merchant_id ": "2", "branch_precision": "", "branch_latitude": "23.0032640000", "branch_id": "26", "branch_name ": "Panyu store, South Village, Panyu district, Sihai district"}], "shop_city": "Guangzhou City"}], "status_desc": "OK "}
The above is the json object returned by the server. This json is a little complicated and involves object nesting and array nesting. The value of the result field is an array with nested objects and arrays. In this case, the solution is actually very simple, that is, processing the content in [] as a set and processing the content in {} as an object.
Therefore, for json parsing, the content in the result [] is composed of two {} objects. Therefore, the following section is defined as a javabean, then it is parsed into an object
{"Rows": [{"branch_long1_":" 113.9760310000 "," branch_userid ":" 273 "," branch_addr ": "L3, yitian holiday Plaza, No. 9028 ShenNan Avenue, Nanshan District, Shenzhen", "branch_status": "1", "is_default": "1", "branch_phone": "13347467909,18875900656 ", "branch_creattime": "0", "city": "Shenzhen city", "branch_park": "parking space in front of the door", "province": "Guangdong", "branch_guidelines ": "11 bus", "branch_updatetime": "0", "merchant_id": "2", "branch_precision": "", "branch_latitude": "22.5375870000 ", "branch_id": "25", "branch_name": "Sihai Panyu store"}], "shop_city": "Shenzhen City "}
The defined javabean is as follows:
public class OrderSeatRows {private List
  
    Rows;private String shop_city;public List
   
     getRows() {return Rows;}public void setRows(List
    
      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 composed of [], that is, rows is also an array, so the rows is treated as a set with the content of {} in it, that is, the following content is also defined as a javabean and parsed to 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;}}
After the above classes are defined, you can start to parse the content of [] First, that is, the method for first parsing the array Gson is as follows: optJSONArray9 () method jo is the JSONObject returned by the server.
JSONArray orderJSONArray = jo.optJSONArray("result");
After the above parsing, we get a JSONArray object, which can be parsed based on the actual situation.
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);
To facilitate the JSONArray object, you can use the getJSONObject () method to obtain all JSONObject objects in JSONArray. After obtaining the JSONObject object, you can parse json into the previously defined object.
Summary: several data models that are generally used in development are described above. In fact, you only need to grasp one principle, see [] parsing into an array, and see {} parsing into an object, then, complicated json data can be easily parsed to prepare data for subsequent development.






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.