Article for reference from: http://blog.csdn.net/binyao02123202/article/details/7540407
The following is a simple example:
Java code
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-The age-to set
*/
public void Setage (int.) {
This.age = age;
}
@Override
Public String toString ()
{
Return name + ":" +age;
}
}
Entities are simple, two fields, and of course the fields in an entity can be list or set type.
Java code
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 JSONString, the value of the Str object for 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:
Java code
Person person = 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:
Java 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 code above uses TypeToken, which is a data type converter provided by Gson, and can support a variety of data collection type conversions.
Just take this excerpt, as a learning footprint, thanks!
JSON data conversion using Gson (list to JSON and JSON to list)