Gson study notes are divided into two parts:
Project Introduction: gson
Gson is an open-source project of Google. It can convert Java objects into JSON, or convert JSON into Java objects.
Gson supports any complex Java objects including objects without source code.
Gson has two basic methods
1) tojson ()-convert a Java object to JSON and convert the object to a JSON expression (string)
2) fromjson ()-convert JSON to a Java object and convert the expression to an object. In fact, I did these two things and did nothing else.
Let's continue to read the code.
1 gson package: http://code.google.com/p/google-gson
You need to import the JAR file gson (download it as needed. Add extenal jar)
PackageShengsiyuan. LXD. gson;
ImportOrg. JSON. jsonobject;
ImportOrg. JUnit. test;
ImportShengsiyuan. LXD. Bean. personbean;
ImportCom. Google. gson. gson;
Public classJsontopersonbean
{
@ Test
Public voidTestjsontopersonbean ()
{
String jsoncontent = "[{'name': 'lixiaodaoaaa', 'age': 22}," +
"{'Name': 'lihao', 'age': 26}," +
"{'Name': 'lib', 'age': 27}]";
Gson =NewGson ();
Personbean [] P = gson. fromjson (jsoncontent, personbean [].Class);
System. Out. println (P [0]. getname ());
}
}
Public classPerson
{
PrivateString name = "lixiaodaoaaa ";
PrivateString age;
PrivateString address;
PrivateList list;
PublicString getname ()
{
ReturnName;
}
PublicPerson (string name, string age, string address, list List)
{
Super();
This. Name = Name;
This. Age = age;
This. Address = address;
This. List = List;
}
Public voidSetname (string name)
{
This. Name = Name;
}
PublicString getage ()
{
ReturnAge;
}
Public voidSetage (string age)
{
This. Age = age;
}
PublicString getaddress ()
{
ReturnAddress;
}
Public voidSetaddress (string address)
{
This. Address = address;
}
PublicList getlist ()
{
ReturnList;
}
Public voidSetlist (list List)
{
This. List = List;
}
}
The above code changes an object to a JSON expression. Changed JSON to an object through gson.PackageShengsiyuan. LXD. gson;
ImportJava. util. arraylist;
ImportJava. util. List;
ImportOrg. JUnit. test;
ImportShengsiyuan. LXD. Bean. person;
ImportCom. Google. gson. gson;
Public classPersonbeantojson
{
@ Test
Public voidTest01 ()
{
Gson G =NewGson ();
List list =NewArraylist ();
List. Add ("El ");
Person P =NewPerson ("lixiaodaoaa", "22", "Shanghai", list );
System. Out. println (G. tojson (p ));
}
}