One
Www.json.org This is the official website of JSON.
First of all, I, we need to download the JSON jar package in Code.google.com/p/google-gson/downloads/list, parse and import the Gson-1.6.jar file into the project you need to parse.
Parse the JSON example as follows:
1, this is the JSON data, "[{\" name\ ": \" michael\ ", \" age\ ": 20},{\" name\ ": \" mike\ ", \" age\ ": 21}]"
2.
Create a Jsonreader object
Jsonreader reader = new Jsonreader (new StringReader (Jsondata));
Start parsing an array
Reader.beginarray ();
Loop to determine if there is no next JSON object
while (Reader.hasnext ()) {
Start parsing JSON objects
Reader.beginobject ();
}
Loop to determine if there is no next key value pair in the JSON object
while (Reader.hasnext ()) {
String tagName = Reader.nextname ();
if (tagname.equal ("name")) {
Name key multiple corresponding value
Reader.nextstring ();
}else if (tagname.equal ("Age")) {
Age key multiple corresponding value
Reader.nextstring ();
}
}
End of JSON object
Reader.endobject ();
}
End of Array parsing
Reader.endarray ();
Two
This example can only be done for JSON objects, not JSON arrays, and JSON arrays need to be converted to JSON objects, which is the next section.
1. There is a JSON object string str = "{\" name\ ": \" michael\ ", \" age\ ": $}", JSON class can directly convert JSON data into Java object
2. Create the User class
public class user{
private String name;
private int age;
public void SetName (String name) {
THIS.name = name;
}
Public String GetName () {
return name;
}
public void Setage (int.) {
This.age = age;
}
public int getage () {
return age;
}
}
3. Create a Gson object
Gson Gson = new Gson ();
The second is an object that indicates which class to convert to
User user = Gson.fromjson (str, user.class);
Sysout.out.println (User.getname);
Sysout.out.println (User.getage);
Three
1. This is the JSON data, String str = "[{\" name\ ": \" michael\ ", \" age\ ": 20},{\" name\ ": \" mike\ ", \" age\ ": 21}]". This JSON data has an array with two JSON objects inside the array.
2. You must first generate a type object, using the following method (user is the user class in the previous section):
Type ListType = new typetoken<linkedlist<user>> () {}.gettype ();
3. Generating Gson objects
Gson Gson = new Gson ();
4. Linkedlist<user> users = Gson.fromjson (str, listtype);
5. Cyclic Iteration LinkedList
for (Iterator Iterator = Users.iterator; Iterator.hasnext ();) {
User user = (user) iterator.next ();
System.out.println (User.getname ());
System.out.println (User.getage ());
}