Using Google's GSON framework in Android to parse JSON data ---- convenient (including code)

Source: Internet
Author: User
Tags tojson

What is JSON: JSON is JavaScript Object Natation. It is a lightweight data exchange format. Like XML, it is a widely used solution for client-side interaction with the server. JSON Object: The Object in JSON starts with "{" and ends. every item in the object is a key-value pair, expressed as "key: value", key-value pairs are separated by commas. for example: {"name": "coolxing", "age" = 24, "male": true, "address": {"street": "huiLongGuan", "city ": "beijing", "country": "china "}}. the key of a JSON Object can only be of the string type, while the value can be of the string, number, false, true, null, Object, or even an array. Yes, nesting may exist. JSON array: JSON array (array) starts with "[" and ends with "]". Each element in the array can be string, number, false, true, null, object objects or even arrays. Elements in arrays are separated by commas. for example, ["coolxing", 24, {"street": "huiLongGuan", "city": "beijing", "country": "china"}]. JSON data parsing: to parse JSON data, you must first specify whether the data to be parsed is a JSON Object or a JSON array, and then determine which resolution technology is used. there are generally two resolution technologies available on the android platform: the built-in org. json package and google's open-source gson library. the following two technologies are used to parse JSON objects and JSON arrays. 1. use the built-in org. json package parsing JS ON object. assume that the JSON data to be parsed is json = "{\" name \ ": \" coolxing \ ", \" age \ "= 24, \" male \ ": true, \ "address \": {\ "street \": \ "huiLongGuan \", \ "city \": \ "beijing \", \ "country \": \ "china \" }}", where \ is used to escape double quotation marks in the expression. first, define two JavaBean: [java] package text.com. bean; public class Address {private String street; private String city; private String country; public Address () {super ();} public Address (String street, String city, String Country) {super (); this. street = street; this. city = city; this. country = country;} public String getStreet () {return street;} public void setStreet (String street) {this. street = street;} public String getCity () {return city;} public void setCity (String city) {this. city = city;} public String getCountry () {return country;} public void setCountry (String country) {this. country = country ;} @ Override public String toString () {return "Address [street =" + street + ", city =" + city + ", country = "+ country +"] ";}} [java] package text.com. bean; public class Person {private String name; private int age; private boolean male; private Address address Address; public Person () {super ();} public Person (String name, int age, boolean male, Address address) {super (); this. name = name; this. ag E = age; this. male = male; this. address = address;} 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 boolean isMale () {return male;} public void setMale (boolean male) {this. male = male;} public Address getAddress () {return address;} public void setAddress (Address address) {this. address = address ;}@ Override public String toString () {return "Person [name =" + name + ", age =" + age + ", male = "+ male +", address = "+ address +"] ";}} first use method 1 to parse the Code as follows: [java] JSONObject jsonObject = new JSONObject (json ); string name = jsonObject. getString ("name"); int age = jsonObject. getInt ("age"); boolean male = jsonObject. getBoolean ("male"); JSONObject addressJSON = JsonObject. getJSONObject ("address"); String street = addressJSON. getString ("street"); String city = addressJSON. getString ("city"); String country = addressJSON. getString ("country"); Address address = new Address (street, city, country); Person person = new Person (name, age, male, address); System. out. println (person); the output of LogCat is Person [name = coolxing, age = 24, male = true, address = Address [street = hui LongGuan, city = beijing, country = china] indicates that the JSON object has been correctly parsed. 2. parse JSON objects using the gson library. assume that the JSON data with resolution is json = "{\" name \ ": \" coolxing \ ", \" age \ "= 24, \" male \ ": true, \ "address \": {\ "street \": \ "huiLongGuan \", \ "city \": \ "beijing \", \ "country \": \ "china \"} ", first go to http://code.google.com/p/google-gson/to download the jarpackage and add it to the project. the specific Parsing Code is as follows: [java] Gson gson = new Gson (); Person person = gson. fromJson (json, Person. class); System. o Ut. println (person); the output of LogCat is Person [name = coolxing, age = 24, male = true, address = Address [street = huiLongGuan, city = beijing, country = china] indicates that the JSON object has been correctly parsed. Is it very simple? 3. use the built-in org. the json package parses the JSON array. assume that the JSON data to be parsed is json = "[{\" name \ ": \" coolxing \ ", \" age \ "= 24, \" male \ ": true, \ "address \": {\ "street \": \ "huiLongGuan \", \ "city \": \ "beijing \", \ "country \": \ "china \" }},{ \ "name \": \ "min \", \ "age \" = 20, \ "male \": false, \ "address \": {\ "street \": \ "heiShiJiao \", \ "city \": \ "daLian \", \ "country \": \ "china \" }}] ", the parsing code is as follows: [java] List <Person> persons = new ArrayList <Person> (); JSONArra Y jsonArray = new JSONArray (json); for (int I = 0; I <jsonArray. length (); I ++) {JSONObject jsonObject = jsonArray. getJSONObject (I); String name = jsonObject. getString ("name"); int age = jsonObject. getInt ("age"); boolean male = jsonObject. getBoolean ("male"); JSONObject addressJSON = jsonObject. getJSONObject ("address"); String street = addressJSON. getString ("street"); String city = addressJSON. getS Tring ("city"); String country = addressJSON. getString ("country"); Address address = new Address (street, city, country); Person person = new Person (name, age, male, address); persons. add (person);} System. out. println (persons); the output of LogCat is [Person [name = coolxing, age = 24, male = true, address = Address [street = huiLongGuan, city = beijing, country = china], Person [name = min, age = 20, male = false, address = Address [Street = heiShiJiao, city = daLian, country = china], indicating that the JSON array has been correctly parsed. 4. parse the JSON Array Using the gson library. the JSON data to be parsed is the same as the preceding one. The code is [java] Gson gson = new Gson (); Type listType = new TypeToken <List <Person> (){}. getType (); List <Person> persons = gson. fromJson (json, listType); LogCat output is [Person [name = coolxing, age = 24, male = true, address = Address [street = huiLongGuan, city = beijing, country = china], Person [name = min, age = 20, Male = false, address = Address [street = heiShiJiao, city = daLian, country = china], indicating that the JSON array has been correctly parsed. new TypeToken <List <Person> (){}. getType (); this Code creates an anonymous subclass object of TypeToken and calls the getType () method of the object. org. there are many other useful APIs in the json package and gson library. You can view the documentation when necessary. for example, you may need to generate json data through a java object or java Collection or array and upload it to the server. Of course, you can construct a json string yourself, but it will be very troublesome. at this time, you can use the related APIs to conveniently complete this task. test Case: [java] package text.com; import java. io. bufferedReader; import java. io. File; import java. io. fileInputStream; import java. io. inputStreamReader; import java. lang. reflect. type; import java. util. list; import text.com. bean. address; import text.com. bean. person; import com. google. gson. gson; import com. google. gson. reflect. typeToken; public class JsonTest {String jsonString = ""; public static void main (String [] args) {// Person p1 = new Person ("zhangsan", 12, true, new Add Ress ("Beijing", "Haidian District", // "No. 30"); // Person p2 = new Person ("zhangsan", 12, true, new Address ("Beijing", "Haidian District", // "No. 30"); // Person p3 = new Person ("zhangsan", 12, true, new Address ("Beijing", "Haidian District", // "No. 30"); // List <Person> list = new ArrayList <Person> (); // list. add (p1); // list. add (p2); // list. add (p3); // Gson gson = new Gson (); // Type typeOfT = new TypeToken <List <Person> (){}. getType (); // String jso N = gson. toJson (list, typeOfT); // System. out. println ("json:" + json); // String str = readTxtFile ("D: \ cjjworkspace \ Test \ json.txt"); // System. out. println ("File Content:" + str); Gson gson = new Gson (); // Type typeOfT = new TypeToken <List <Person> (){}. getType (); // List <Person> personList = gson. fromJson (str, typeOfT); Person p1 = new Person ("zhangsan", 12, true, new Address ("Beijing", "Haidian District", "30 ")); type t YpeOfT = new TypeToken <Person> (){}. getType (); String str = gson. toJson (p1, typeOfT); System. out. println (str);} public static String readTxtFile (String filePath) {String encoding = "UTF-8"; StringBuilder sb = new StringBuilder (); try {File file = new File (filePath); if (file. isFile () & file. exists () {// determine whether the file exists InputStreamReader read = new InputStreamReader (new FileInputStream (file), encodin G); // considering the encoding format BufferedReader bufferedReader = new BufferedReader (read); String str = ""; while (str = bufferedReader. readLine ())! = Null) {sb. append (str);} read. close (); return sb. toString ();} else {System. out. println ("the specified file cannot be found"); return null ;}} catch (Exception e) {System. out. println ("An error occurred while reading the file content"); e. printStackTrace ();} return sb. toString () ;}}with: gson-2.2.4.jar gson-2.2.4-javadoc.jar gson-2.2.4-sources.jar

Related Article

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.