最近要使用java来操作Json数据,虽然Json用过几次,但一直没有好好总结,趁这次来总结一下java操作Json数据。Java操作Json有很多工具包,地址为http://www.json.org/,可以自己上去挑选。
这里我使用第一个org.json,最新源码地址为:https://github.com/douglascrockford/JSON-java,可以自己去下载,我也会在附件上传。下载源码后放进工程即可,包名为org.json
我们要操作的Json数据如下:
{"total":2,"class":"二年级","members":[{"age":18,"name":"李小红","score":95},{"age":28,"name":"王尼玛","score":85}]}
我们先用CreateJson()方法生成Json数据,然后把所有属性都解析出来。
package Myclass;
import org.json.JSONArray;
import org.json.JSONObject;
public class Test {
public static void main(String[] args) { <br style="word-wrap:break-word">
//解析Json--传入Json字符串 <br style="word-wrap:break-word">
JSONObject my_json=new JSONObject(CreateJson()); <br style="word-wrap:break-word">
int total=my_json.getInt("total"); <br style="word-wrap:break-word">
System.out.println("总数为:"+total); <br style="word-wrap:break-word">
<br style="word-wrap:break-word">
String class_name=my_json.getString("class"); <br style="word-wrap:break-word">
System.out.println("班级为:"+class_name); <br style="word-wrap:break-word">
<br style="word-wrap:break-word">
JSONArray members=my_json.getJSONArray("members"); <br style="word-wrap:break-word">
for(int i=0;i<members.length();i++) <br style="word-wrap:break-word">
{ <br style="word-wrap:break-word">
JSONObject member=(JSONObject)members.get(i); <br style="word-wrap:break-word">
System.out.println("姓名:"+member.getString("name")+" 年龄:"+member.getInt("age") <br style="word-wrap:break-word">
+" 成绩:"+member.getInt("score")); <br style="word-wrap:break-word">
} <br style="word-wrap:break-word">
<br style="word-wrap:break-word">
} <br style="word-wrap:break-word">
<br style="word-wrap:break-word">
public static String CreateJson() <br style="word-wrap:break-word">
{ <br style="word-wrap:break-word">
JSONObject my_json=new JSONObject(); <br style="word-wrap:break-word">
my_json.put("class", "二年级"); <br style="word-wrap:break-word">
my_json.put("total", 2); <br style="word-wrap:break-word">
<br style="word-wrap:break-word">
JSONArray members=new JSONArray(); <br style="word-wrap:break-word">
//第一个同学 <br style="word-wrap:break-word">
JSONObject member1=new JSONObject(); <br style="word-wrap:break-word">
member1.put("name", "李小红"); <br style="word-wrap:break-word">
member1.put("age", 18); <br style="word-wrap:break-word">
member1.put("score", 95); <br style="word-wrap:break-word">
members.put(member1); <br style="word-wrap:break-word">
//第二个同学 <br style="word-wrap:break-word">
JSONObject member2=new JSONObject(); <br style="word-wrap:break-word">
member2.put("name", "王尼玛"); <br style="word-wrap:break-word">
member2.put("age", 28); <br style="word-wrap:break-word">
member2.put("score", 85); <br style="word-wrap:break-word">
members.put(member2); <br style="word-wrap:break-word">
my_json.put("members", members); <br style="word-wrap:break-word">
<br style="word-wrap:break-word">
return my_json.toString(); <br style="word-wrap:break-word">
} <br style="word-wrap:break-word">
}
复制代码
运行结果为: