How to use Android Gson to convert JSON structures to each other

Source: Internet
Author: User
Tags string back tojson

Convert data structures such as arrays, objects, LIST,MAP, etc. into JSON strings

Import Java.lang.reflect.type;import java.util.arraylist;import Java.util.date;import Java.util.HashMap;import Java.util.list;import Java.util.map;import Com.google.gson.gson;import Com.google.gson.reflect.typetoken;public    Class Main {public static class student{private String name;    int age;        Private String address;    Private Date dateOfBirth; Public Student () {} public Student (String name, int age,string address, Date dateofbirth) {this.name = name        ;        This.age=age;        this.address = address;    This.dateofbirth = dateOfBirth; } public int Getage () {return age;} public void Setage (int.) {this.age = age;}    Public String GetName () {return name;    } public void SetName (String name) {this.name = name;    } public String getaddress () {return address;    The public void setaddress (String address) {this.address = address;    Public Date Getdateofbirth () {return dateofbirth; } PublIC void Setdateofbirth (Date dateofbirth) {This.dateofbirth = dateOfBirth;     }}public static void Main (string[] args) {Gson gson=new Gson ();/* Array converted to JSON String */int[] numbers = {1, 1, 2, 3, 5, 8, 13};     String[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};      String Numbersjson=gson.tojson (numbers);        String Daysjson = Gson.tojson (days);      SYSTEM.OUT.PRINTLN ("array into JSON string:");      System.out.println ("Numbersjson =" + Numbersjson);               System.out.println ("Daysjson =" + Daysjson);        /*list into JSON string, element is String */list<string> names = new arraylist<string> ();        Names.add ("Alice");        Names.add ("Bob");        Names.add ("Carol");     Names.add ("Mallory");     String jsonnames = Gson.tojson (names);     SYSTEM.OUT.PRINTLN ("list is converted to JSON string, element is string");                  System.out.println ("jsonnames =" + jsonnames);    /*list converted to JSON string, element is Object */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);     String jsonstudents = Gson.tojson (students);     SYSTEM.OUT.PRINTLN ("list is converted to JSON string, element is Object");     System.out.println ("jsonstudents =" + jsonstudents);         Converts JSON string into a collection of Student object.     Type type = new Typetoken<list<student>> () {}.gettype ();     System.out.println ("JSON string converted to list, element is Object");     list<student> studentlist = Gson.fromjson (jsonstudents, type);     for (Student student:studentlist) {System.out.println ("student.getname () =" + Student.getname ()); }/*map into JSON string, value is String */map<string, string> colors = new hashmap<string, string> ()        ; ColorS.put ("BLACK", "#000000");        Colors.put ("RED", "#FF0000");        Colors.put ("GREEN", "#008000");        Colors.put ("BLUE", "#0000FF");        Colors.put ("YELLOW", "#FFFF00");                Colors.put ("White", "#FFFFFF");        String Jsonmap = Gson.tojson (colors);        System.out.println ("Map converted to JSON string, value is string");        SYSTEM.OUT.PRINTLN ("JSON =" + Jsonmap);        Convert JSON string back to Map.        Type type1 = new typetoken<map<string, string>> () {}.gettype ();        map<string, string> map = Gson.fromjson (Jsonmap, type1);        System.out.println ("JSON string converted to Map,value is a string");        For (String Key:map.keySet ()) {System.out.println ("Map.get =" + map.get (key));        }/*map into JSON string, value is Object */map<string, student> studentmap = new hashmap<string, student> ();        Studentmap.put ("Alice", a);        Studentmap.put ("Bob", b);        Studentmap.put ("Carol", c);        Studentmap.put ("Mallory", D); String Jsonmap1 = Gson.tojson (Studentmap);        System.out.println ("Map converted to JSON string, value is Object");        SYSTEM.OUT.PRINTLN ("JSON =" + Jsonmap1);        Convert JSON string back to Map.        Type type11 = new typetoken<map<string, student>> () {}.gettype ();        System.out.println ("JSON string converted to Map,value is Object");        map<string, student> map1 = Gson.fromjson (Jsonmap1, TYPE11);        For (String Key:map1.keySet ()) {System.out.println ("Map1.get =" + map1.get (key). GetName ()); }                                        }}
Output Result:

The array is converted to a JSON string: Numbersjson = [1,1,2,3,5,8,13]daysjson = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]list converted to JSON strings, The element is the string jsonnames = ["Alice", "Bob", "Carol", "Mallory"]list converted to a JSON string, the element is Object jsonstudents = [{"Name": "Alice", "Age": 20, " Address ":" Apple St "," dateOfBirth ":" Nov 1, 3900 12:00:00 AM "},{" name ":" Bob "," Age ":," Address ":" Banana St "},{" name ":" Carol "," Age ":" Address ":" Grape St "," dateOfBirth ": June, 3900 12:00:00 AM"},{"name": "Mallory", "Age": "Address" : "Mango St"}]json string converted to list, element is Object Student.getname () = alicestudent.getname () = bobstudent.getname () = Carolstudent.getname () = Mallorymap into JSON string, value is string json = {"White": "#FFFFFF", "BLUE": "#0000FF", "YELLOW": "#FFFF00" , "GREEN": "#008000", "BLACK": "#000000", "RED": "#FF0000" the}json string converted to Map,value is Map.get = #FFFFFFmap. Get = # 0000ffmap.get = #FFFF00map. Get = #008000map. Get = #000000map. Get = #FF0000Map转化成Json串, value is the object json = {"Mallory": {"name": "Mallory", "age": +, "address": "Mango St"}, "Alice": {"name": "Alice", "Age": +, "address": "Apple St", "dateOfBirth": " Nov 1, 3900 12:00:00 AM "}," Bob ": {" name ":" Bob "," Age ": All," Address ":" Banana St "}," Carol ": {" name ":" Carol "," Age ": 42," Address ":" Grape St "," dateOfBirth ":" June, 3900 12:00:00 AM "}}json string converted to Map,value is Object map1.get = Mallorymap1.get = Alicemap1.get = Bobmap1.get = Carol

It can be observed that:

1, a single object Object,json string is a jsonobject, the colon ":" Before the key is the variable name of the Java object, the colon ":" After the value is a Java object variable values

2, arrays and List,json strings are a Jsonarray

3,map JSON string is a jsonobject, the colon ":" The preceding key is the key value of the map, the colon ":" After the value is the value of the map

Second, when the JSON string is converted to a Java object, the main thing to see is the colon ":" What is the data type of the value behind it, so what is the field type of the Java object, the data type of value and the data type of the field are the corresponding

{"Success": TRUE, "data": {"list": [{"DataType": 0, "distance": 435.2473470455821, "Isfav": 0, "Parkcode": "0270000558", "Parkname": Wuhan Financial Harbor Road Field "," Parkid ": 558," remark ":", "Parktype": 0 , "responsible": "", "Responsetel": "13297062676", "Consulttel": "", "Coordinatex": 114.428102, "Coordinatey": 30.462254 , "coordinateentrance": "", "Rateinfo": "Weekday", "Introduce": "", "AppState": 3, "Paymentnoticeminute": 0, "Rentcount": 0, " Rentswitch ": 0," Spacecount ": TotalCount," ImageName ":", "" Fullimage ":", "Unitfee": 0.0, "unit": 0, "isroadside ": 0," rentovertimetimes ": 0.0," Reservationkeeptime ": 0," Supportpaytype ": 0," Address ":" Optics Valley Avenue Financial Port "," state ": 1}, {" Dat Atype ": 0," distance ": 568.3080108478586," isfav ": 0," Parkcode ":" 0270000249 "," Parkname ":" Wuhan Optics Valley Financial Port parking Lot "," Parkid ": 249," Remark ":", "Parktype": 3, "" "Responsible": "", "Responsetel": "123456789", "Consulttel": "", "Coordinatex": 114.427728, " Coordinatey ": 30.460922," coordinateentrance ":" 114.427005,30.461393,1,1;114.427863,30.462163,1,1;114.428469,30.462171,1,1;114.427885,30.461404,2,1;114.428514,30.461424,2,1; 114.428851,30.461397,3,1,1;114.427351,30.462163,3,1,1; "," Rateinfo ":" Daytime 3 yuan/hour \ Night 1 Yuan/hour "," introduce ":" "," appState ": Paymentnoticeminute": 2, "Rentcount": 0, "Rentswitch": 1, "Spacecount": -95, "totalcount": +, "imageName": "7.jpg "," Fullimage ":"/picture/park/249/7.jpg "," Unitfee ": 0.01," unit ": $," isroadside ": 0," rentovertimetimes ": 0.0," Reservationkeeptime ": 0," Supportpaytype ": 0," address ": Wuhan Optics Valley Financial Port, Wuhan Optics Valley Financial Port B4 12 floor," state ": 1}]}}
Package Com.hust.map;public class Park {int dataType;     int rentcount;     int Parkcode;     String parkname;//parking lot name int parkid;     String remark;     int parktype;     String responsible;     String Responsetel;     String Consulttel;     Double coordinatex;//longitude double coordinatey;//latitude String coordinateentrance;     String rateinfo;//charge standard string introduce;     int appState;     int Paymentnoticeminute;     int spacecount;//can rent a car bit int totalcount;//Total parking space String imageName;     String Fullimage;     int reservationkeeptime;     int isroadside;     Double rentovertimetimes;     Double Unitfee;     int unit;     int rentswitch;     int supportpaytype;     int isfav;     Double distance;//distance String address;//address int state; Public double Getcoordinatex () {return coordinatex;} public void Setcoordinatex (double coordinatex) {This.coordinatex = Coordinatex;} Public double Getcoordinatey () {return coordinatey;} public void Setcoordinatey (double coOrdinatey) {This.coordinatey = Coordinatey;} Public String Getparkname () {return parkname;} public void Setparkname (String parkname) {this.parkname = Parkname;} public int Getspacecount () {return spacecount;} public void Setspacecount (int spacecount) {this.spacecount = Spacecount;} public int Gettotalcount () {return totalcount;} public void Settotalcount (int totalcount) {this.totalcount = TotalCount;} Public String Getrateinfo () {return rateinfo;} public void Setrateinfo (String rateinfo) {this.rateinfo = Rateinfo;} Public double getdistance () {return distance;} public void setdistance (double distance) {this.distance = distance;} Public String getaddress () {return address;} public void setaddress (String address) {this.address = address;} Public Park (int dataType, int rentcount, int parkcode, String parkname,int Parkid, string remark, int parktype, string res Ponsible,string Responsetel, String Consulttel, double coordinatex,double Coordinatey, String coordinateentrance, String rateinfo,string IntroduCE, int appState, int paymentnoticeminute,int spacecount, int totalcount, string imageName, String Fullimage,int Reservati onkeeptime, int isroadside, double rentovertimetimes,double unitfee, int unit, int rentswitch, int supportpaytype,int isFa  V, double distance, String address, int state) {super (); this.datatype = Datatype;this.rentcount = Rentcount;this.parkcode = Parkcode;this.parkname = Parkname;this.parkid = Parkid;this.remark = Remark;this.parktype = parkType;this.responsible = Responsible;this.responsetel = Responsetel;this.consulttel = Consulttel;this.coordinatex = CoordinateX; This.coordinatey = Coordinatey;this.coordinateentrance = Coordinateentrance;this.rateinfo = RateInfo;this.introduce = Introduce;this.appstate = Appstate;this.paymentnoticeminute = Paymentnoticeminute;this.spacecount = SpaceCount; This.totalcount = Totalcount;this.imagename = Imagename;this.fullimage = Fullimage;this.reservationkeeptime = Reservationkeeptime;this.isroadside = Isroadside;this.rentovertimetimes = Rentovertimetimes;this.unitfee = Unitfee;this.unit = Unit;this.rentswitch = Rentswitch;this.supportpaytype = supportpaytype;this.isfav = Isfav;this.distance = distance;this.address = Address;this.state = State;} public int Getdatatype () {return dataType;} public void Setdatatype (int dataType) {this.datatype = DataType;} public int Getrentcount () {return rentcount;} public void Setrentcount (int rentcount) {this.rentcount = Rentcount;} public int Getparkcode () {return parkcode;} public void Setparkcode (int parkcode) {this.parkcode = Parkcode;} public int Getparkid () {return parkid;} public void Setparkid (int parkid) {this.parkid = Parkid;} Public String Getremark () {return remark;} public void Setremark (String remark) {This.remark = remark;} public int Getparktype () {return parktype;} public void Setparktype (int parktype) {this.parktype = Parktype;} Public String getresponsible () {return responsible;} public void Setresponsible (String responsible) {this.responsible = responsible;} Public String GetResponsetel () {return responsetel;} public void Setresponsetel (String responsetel) {This.responsetel = Responsetel;} Public String Getconsulttel () {return consulttel;} public void Setconsulttel (String consulttel) {This.consulttel = Consulttel;} Public String getcoordinateentrance () {return coordinateentrance;} public void Setcoordinateentrance (String coordinateentrance) {this.coordinateentrance = coordinateentrance;} Public String Getintroduce () {return introduce;} public void Setintroduce (String introduce) {this.introduce = introduce;} public int getappstate () {return appState;} public void setappstate (int appState) {this.appstate = appState;} public int Getpaymentnoticeminute () {return paymentnoticeminute;} public void Setpaymentnoticeminute (int paymentnoticeminute) {this.paymentnoticeminute = Paymentnoticeminute;} Public String Getimagename () {return imageName;} public void Setimagename (String imageName) {this.imagename = ImageName;} Public String Getfullimage () {return fullimage;} public void SetFullimage (String fullimage) {this.fullimage = Fullimage;} public int Getreservationkeeptime () {return reservationkeeptime;} public void setreservationkeeptime (int reservationkeeptime) {this.reservationkeeptime = Reservationkeeptime;} public int getisroadside () {return isroadside;} public void setisroadside (int isroadside) {this.isroadside = Isroadside;} Public double Getrentovertimetimes () {return rentovertimetimes;} public void Setrentovertimetimes (double rentovertimetimes) {this.rentovertimetimes = Rentovertimetimes;} Public double Getunitfee () {return unitfee;} public void Setunitfee (double unitfee) {this.unitfee = Unitfee;} public int Getunit () {return unit;} public void setunit (int unit) {this.unit = unit;} public int Getrentswitch () {return rentswitch;} public void Setrentswitch (int rentswitch) {this.rentswitch = Rentswitch;} public int Getsupportpaytype () {return supportpaytype;} public void Setsupportpaytype (int supportpaytype) {this.supportpaytype = Supportpaytype;} public int getisfav () {RETurn isfav;} public void setisfav (int isfav) {this.isfav = isfav;} public int getState () {return state;}         public void SetState (int.) {this.state = state;} }
Datafromnetwork.java

Package Com.hust.map;import Java.util.arraylist;import Java.util.hashmap;public class Datafromnetwork {      Boolean Success;      hashmap<string,arraylist<park>> data;}


Datafromnetwork Mdatafromnetwork=mgson.fromjson (mparksstring, Datafromnetwork.class); Arraylist<park> mparkslist=mdatafromnetwork.data.get ("list");


How to use Android Gson to convert JSON structures to each other

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.