Gson: Conversion of objects to JSON

Source: Internet
Author: User

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

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.