Gson and other existing Java JSON class libraries have the greatest difference when Gson need to serialize the entity classes do not need to use 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 class Person {
private String name;
private int age;
/**
* @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 of the age to set
*/
public void Setage (int age) {
This.age = age;
}
@Override
Public String toString ()
{
Return name + ":" +age;
}
}
The entity is very simple, two fields, of course, the field in the entity can also be a list or set type.
Gson Gson = new Gson ();
list<person> persons = new arraylist<person> ();
for (int i = 0; i < i++) {
Person p = new person ();
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, with the Str object value of the above code:
[{' 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}]
Here's a look at Gson deserialization, Gson provides a Fromjson () method for implementing a method from JSON-related objects to Java entities.
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.
First of all, see:
For example, the JSON string is: [{' Name ': ' NAME0 ', ' age ': 0}]
Code:
Person person = Gson.fromjson (str, person.class);
provides two parameters, namely, 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, new typetoken<list<person>> () {}.gettype ());
for (int i = 0; i < ps.size (); i++)
{
Person p = ps.get (i);
System.out.println (P.tostring ());
}
You can see that the above code uses TypeToken, which is a data type converter provided by Gson, and can support various data collection type conversions.