1. Use Gson's Tojson () method to convert the object to a JSON string:
Method: Gson.tojson (Object src)
Person.java
Public classPerson {PrivateString name; Private intAge ; PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; }
Gsontest.java
Public classGsontest { Public Static voidMain (string[] args) {Gson Gson=NewGson (); List<Person> persons =NewArraylist<person>(); Person P1=NewPerson (); P1.setname ("Zhang San"); P1.setage (23); Person P2=NewPerson (); P2.setname ("John Doe"); P2.setage (24); Persons.add (p1); Persons.add (p2); SYSTEM.OUT.PRINTLN (persons); String Str= Gson.tojson (persons);//convert object to JSONSystem.out.println (str);}}
The output is: [[email protected], [email protected]]
[{' name ': ' Zhang San ', ' age ': 23},{' name ': ' John Doe ', ' age ': 24}]
The direct Print object actually prints the string returned by the ToString method of object, which consists of the class name (the object is an instance of the class), the token "@", and the unsigned hexadecimal representation of the object's hash code. i.e.: GetClass (). GetName () + ' @ ' + integer.tohexstring (hashcode ())
2, Gson: Gson provides the Fromjson () method to implement a method from a JSON-related object to a Java entity.
Method: Gson.fromjson (String json, class<person> Classoft) throws Jsonsyntaxexception
Jsontest.java
Public class jsontest { publicstaticvoidthrows jsonexception{ New Jsonobject (); Pjson.put ("name", "Harry"); Pjson.put ("age", +); System.out.println (Pjson); New Gson (); = Gson.fromjson (pjson.tostring (), person. Class); SYSTEM.OUT.PRINTLN (P); }}
Output Result:
{"Age": +, "name": "Harry"}
[Email protected]
Jsonarray Convert to List type:
Method: Gson.fromjson (String json, Type Typeoft) throws Jsonsyntaxexception
Jsonarraytest.java
Public classJsonarraytest { Public Static voidMain (string[] args)throwsjsonexception{jsonobject P01=NewJsonobject (); P01.put ("Name", "Zhao Liu"); P01.put ("Age", 26); Jsonobject P02=NewJsonobject (); P02.put ("Name", "Qin Qi"); P02.put ("Age", 27); Jsonarray ja=NewJsonarray (); Ja.put (P01); Ja.put (P02); System.out.println (JA); Gson Gson=NewGson (); List<Person> PS = Gson.fromjson (ja.tostring (),NewTypetoken<list<person>>() {}.gettype ()); SYSTEM.OUT.PRINTLN (PS); }}
The output gets:
[{"Age": +, "name": "Zhao Liu"},{"Age": "Name": "Qin Qi"}]
[[Email protected], [email protected]]
The code above uses TypeToken, which is a data type converter provided by Gson that supports a variety of data collection type conversions.
Gson: Conversion of objects to JSON