The recent use of Java to manipulate JSON data, although JSON used a few times, but has not been well summarized, while this time to summarize the Java operation JSON data. Java operation JSON has a lot of toolkit, the address is http://www.json.org/, you can pick up yourself.
Here I use the first Org.json, the latest source address is:Https://github.com/douglascrockford/JSON-java, you can download, I will also upload in the attachment. Download the source code and put it into the project, the package is named Org.json
The JSON data we want to manipulate is as follows:
{"Total": 2, "Class": "Second Grade", "members": [{"Age": "" "," Name ":" Li Xiaohong "," Score ": 95},{" Age ": 85," name ":" Wang Nima "," score ": +/-)}
We first use the Createjson () method to generate the JSON data and then parse all the properties.
Package Myclass;
Import Org.json.JSONArray;
Import Org.json.JSONObject;
public class Test {
public static void Main (string[] args) {
Parse json--incoming JSON string
Jsonobject my_json=new Jsonobject (Createjson ());
int Total=my_json.getint ("total");
System.out.println ("total:" +total);
String class_name=my_json.getstring ("class");
SYSTEM.OUT.PRINTLN ("Class for:" +class_name);
Jsonarray Members=my_json.getjsonarray ("members");
for (int i=0;i<members.length (); i++)
{
Jsonobject member= (jsonobject) members.get (i);
System.out.println ("Name:" +member.getstring ("name") + "Age:" +member.getint ("ages")
+ "Score:" +member.getint ("score"));
}
}
public static String Createjson ()
{
Jsonobject my_json=new jsonobject ();
My_json.put ("Class", "Second Grade");
My_json.put ("Total", 2);
Jsonarray members=new Jsonarray ();
The first classmate of the
Jsonobject member1=new jsonobject ();
Member1.put ("name", "Li Xiaohong");
Member1.put ("Age", 18);
Member1.put ("Score", 95);
Members.put (Member1);
A second classmate
Jsonobject member2=new jsonobject ();
Member2.put ("name", "Wang Nima");
Member2.put ("Age", 28);
Member2.put ("Score", 85);
Members.put (MEMBER2);
My_json.put ("members", members);
return my_json.tostring ();
}
}
Copy Code
The result of the operation is:
Java Operation JSON data