Android JSON gson Parsing

Source: Internet
Author: User
Tags tojson
What is JSON:

JavaScript Object Notation is a lightweight data exchange format.


Differences from XML:

+ JSON is smaller than XML in size.

+ More convenient interaction between JSON and JavaScript

+ JSON is much faster than XML.

+ JSON is less descriptive than XML.


JSON structure:

(1) object: unordered "'name/value' pair" set. An object starts with "{" and ends. Each "name" is followed by a ":", and "," is used to separate the "name/value" pairs.
(2) array: an ordered set of values. An array ends with "[" and. Values are separated by commas. Values can be string, number, true, false, null, object, or array enclosed by double quotation marks ). These structures can be nested.


Gson method: array <---> JSON

int[] numbers = {1, 1, 2, 3, 5, 8, 13};String[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};Gson gson = new Gson();String numbersJson = gson.toJson(numbers);String daysJson = gson.toJson(days);System.out.println("numbersJson = " + numbersJson);//numbersJson = [1,1,2,3,5,8,13]System.out.println("daysJson = " + daysJson);//daysJson = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]int[] fibonacci = gson.fromJson(numbersJson, int[].class);String[] weekDays = gson.fromJson(daysJson, String[].class);

Set <---> JSON

List<String> names = new ArrayList<String>();names.add("Alice");names.add("Bob");names.add("Carol");names.add("Mallory");Gson gson = new Gson();String jsonNames = gson.toJson(names);//jsonNames = ["Alice","Bob","Carol","Mallory"]Student a = new Student("Alice", "Apple St", new Date(2000, 10, 1));Student b = new Student("Bob", "Banana St", null);Student c = new Student("Carol", "Grape St", new Date(2000, 5, 21));Student d = new Student("Mallory", "Mango St", null);List<Student> students = new ArrayList<Student>();students.add(a);students.add(b);students.add(c);students.add(d);gson = new Gson();String jsonStudents = gson.toJson(students);//[{"name":"Alice","address":"Apple St","dateOfBirth":"Nov 1, 3900 12:00:00 AM"},{"name":"Bob","address":"Banana St"},{"name":"Carol","address":"Grape St","dateOfBirth":"Jun 21, 3900 12:00:00 AM"},{"name":"Mallory","address":"Mango St"}]Type type = new TypeToken<List<Student>>(){}.getType();List<Student> studentList = gson.fromJson(jsonStudents, type);Map<--->JsonMap<String, String> colours = new HashMap<String, String>();colours.put("BLACK", "#000000");colours.put("RED", "#FF0000");colours.put("GREEN", "#008000");colours.put("BLUE", "#0000FF");colours.put("YELLOW", "#FFFF00");colours.put("WHITE", "#FFFFFF");Gson gson = new Gson();String json = gson.toJson(colours);//{"WHITE":"#FFFFFF","BLUE":"#0000FF","YELLOW":"#FFFF00","GREEN":"#008000","BLACK":"#000000","RED":"#FF0000"}Type type = new TypeToken<Map<String, String>>(){}.getType();Map<String, String> map = gson.fromJson(json, type);for (String key : map.keySet()) {    System.out.println("map.get = " + map.get(key));}

Object <---> JSON

Student student = new Student("Duke", "Menlo Park", dob.getTime());Gson gson = new Gson();String json = gson.toJson(student);//{"name":"Duke","address":"Menlo Park","dateOfBirth":"Feb 1, 2000 12:00:00 AM"}Gson gson = new Gson();Student student = gson.fromJson(json, Student.class);


Nested Parsing
Package test0328; import Java. util. arrays; public class person {/** {"phone": ["112233", "445566"], // array "name": "android ", // string "Age": 5, // value "Address": {"country": "China", "Province": "Shanghai "}, // object "married": false // Boolean value}, **/private string [] Phone;/*** @ return the address */Public Address getaddress () {return address;}/*** @ Param address * the address to set */Public void setaddress (Address) {This. address = address;} private string name; private int age; private Address = NULL; private Boolean married;/*** @ return the phone */Public String [] getphone () {return phone;}/*** @ Param phone * the phone to set */Public void setphone (string [] Phone) {This. phone = phone;}/** (non-javadoc) ** @ see Java. lang. object # tostring () */@ overridepublic string tostring () {return "person [Phone =" + arrays. tostring (phone) + ", name =" + name + ", age =" + age + ", address =" + address + ", married = "+ Married +"] ";}/*** @ return the name */Public String getname () {return name ;} /*** @ Param name * the name to set */Public void setname (string name) {This. name = Name;}/*** @ return the age */Public int getage () {return age ;} /*** @ Param age * the age to set */Public void setage (INT age) {This. age = age;}/*** @ return the married */Public Boolean ismarried () {return married ;} /*** @ Param married * The Married To Set */Public void setmarried (Boolean married) {This. married = married ;}}


Package test0328; public class address {// "Address": {"country": "China", "Province": "Shanghai"}, // object private string country; private string province;/*** @ return the country */Public String getcountry () {return country ;} /*** @ Param country * the country to set */Public void setcountry (string country) {This. country = country;}/*** @ return the province */Public String getprovince () {return province ;} /*** @ Param province * the province to set */Public void setprovince (string province) {This. province = province;}/** (non-javadoc) ** @ see Java. lang. object # tostring () */@ overridepublic string tostring () {return "Address [Country =" + country + ", Province =" + province + "]" ;}}


Package test0328; import Java. io. stringreader; import COM. google. gson. gson; import COM. google. gson. stream. jsonreader; public class JSON {/* [{"phone": ["112233", "445566"], // array "name": "android ", // string "Age": 5, // value "Address": {"country": "PRC", "Province": "Shanghai "}, // object "married": false // Boolean}, {"phone": ["778899", "224466"], // array "name": "Linux ", // string "Age": 15, // value "Address": {"country": "USA", "Province": "NY "}, // object "married": True // Boolean}] */Private Static final string JSON = "[{\" phone \ ": [\" 112233 \", \ "445566 \"], \ "Name \": \ "android \", \ "Age \": 5, \ "address \" :{\ "country \": \ "China \", \ "province \": \ "Shanghai \" },\ "Married \": false },{ \ "phone \": [\ "778899 \", \ "224466 \"], \ "Name \": \ "Linux \", \ "Age \": 15, \ "address \": {\ "country \": \ "USA \", \ "province \": \ "NY \"}, \ "Married \": true}] "; private Static gson = new gson (); public static void main (string [] ARGs) throws exception {jsonreader reader = new jsonreader (New stringreader (JSON); reader. beginarray (); // start array while (reader. hasnext () {// loop reader. beginobject (); // start object person = new person (); While (reader. hasnext () {// loop string tagname = reader. nextname (); If ("phone ". equals (tagname) {reader. beginarray (); string [] phones = new string [2]; phones [0] = reader. nextstring (); phones [1] = reader. nextstring (); person. setphone (Phones); reader. endarray ();} else if ("name ". equals (tagname) {person. setname (reader. nextstring ();} else if ("age ". equals (tagname) {person. setage (reader. nextint ();} else if ("Address ". equals (tagname) {reader. beginobject (); Address = new address (); While (reader. hasnext () {int I = 0; string tagname2 = reader. nextname (); If ("country ". equals (tagname2) {address. setcountry (reader. nextstring ();} else {address. setprovince (reader. nextstring ();} person. setaddress (Address); reader. endobject ();} else if ("married ". equals (tagname) {person. setmarried (reader. nextboolean ();} reader. endobject (); system. out. println (person);} reader. endarray ();} public static int [] intsfromjson (string JSON) {return gson. fromjson (JSON, int []. class);} public static string [] stringsfromjson (string JSON) {return gson. fromjson (JSON, string []. class );}}


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.