Gson convert an object to a JSON-formatted string

Source: Internet
Author: User




Recently I was working on a Java Web service project and needed to use Jason, who was not particularly proficient in Java, and began to search the JSON class libraries of some Java platforms.

Found Google's Gson, because before protocolbuf some understanding, with some curiosity, I began to use the Gson.

By comparison, Gson and other existing Java JSON class libraries are most different when Gson need to serialize an entity class without using annotation to identify the fields that need to be serialized, while Gson can flexibly configure the fields that need to be serialized by using annotation.

The following is a simple example:

 Public classPerson {

PrivateString name;
Private intAge ;

/**
* @returnThe name
*/
PublicString GetName () {
returnname;
}

/**
* @paramname the name to set
*/
Public voidsetName (String name) {
This. Name=name;
}

/**
* @returnThe Age
*/
Public intGetage () {
returnAge ;
}

/**
* @paramAge-The age-to set
*/
Public voidSetage (intAge ) {
This. Age=Age ;
}

@Override
PublicString toString ()
{
returnname+ ":" +Age
}
}

Entities are simple, two fields, and of course the fields in an entity can be list or set type.

Gson Gson= NewGson ();
List< Person>Persons= NewArrayList< Person>();
for (intI= 0; I< Ten; I++) {
Person P= NewPerson ();
P.setname ("name" +i);
P.setage (i* 5);
Persons.add (P);
}
String Str=Gson.tojson (persons);

The above code focuses on the Gson object, which provides the Tojason () method to convert the object to a JSON string, the value of the Str object of the above code is:

[{' name ': ' NAME0 ', ' age ': 0},{' name ': ' name1 ', ' age ': 5},{' name ': ' name2 ', ' age ': 10},{' name ': ' Name3 ', ' age ': 15},{' name ' : ' Name4 ', ' age ': 20},{' name ': ' Name5 ', ' age ': 25},{' name ': ' Name6 ', ' age ': 30},{' name ': ' Name7 ', ' age ': 35},{' name ': ' Name8 "," Age ": 40},{" name ":" Name9 "," Age ": 45}]

Very standard JSON data, very simple, hehe.

The following is a look at the deserialization of Gson, Gson provides the Fromjson () method for implementing a method from a JSON-related object to a Java entity.

In everyday applications, we typically encounter two situations, turning into a single entity object and converting it into a list of objects or other structures.

Let's look at the first type:

For example, the JSON string is: [{"Name": "NAME0", "Age": 0}]

Code:

= Gson.fromjson (str, person. class );

Provides two parameters, the JSON string, and the type of object that needs to be converted.

Second, convert to list type:

Code:

List< Person>PS=Gson.fromjson (str,NewTypeToken<List< Person>>() {}.gettype ());
for(intI= 0; I<ps.size (); I++)
{
Person P=Ps.get (i);
System.out.println (P.tostring ());
}

You can see that the code above uses TypeToken, which is a data type converter provided by Gson, and can support a variety of data collection type conversions.

Gson basic use is so much, as to annotation aspects can refer to Gson official documents, hope to beginner Java and Gson classmates help.


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Gson convert an object to a JSON-formatted string

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.