@Yano
2016-07-16T16:12:26.000000Z
字数 1744
阅读 2526
Java
JavaScript Object Notation,一种轻量级的数据交换格式
。
易于人阅读和编写,同时也易于机器解析和生成
(一般用于提升网络传输速率)。
{"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"}
{
"people":[
{"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"},
{"firstName":"Jason","lastName":"Hunter","email":"bbbb"},
{"firstName":"Elliotte","lastName":"Harold","email":"cccc"}
]
}
{
"programmers": [{
"firstName": "Brett",
"lastName": "McLaughlin",
"email": "aaaa"
}, {
"firstName": "Jason",
"lastName": "Hunter",
"email": "bbbb"
}, {
"firstName": "Elliotte",
"lastName": "Harold",
"email": "cccc"
}],
"authors": [{
"firstName": "Isaac",
"lastName": "Asimov",
"genre": "sciencefiction"
}, {
"firstName": "Tad",
"lastName": "Williams",
"genre": "fantasy"
}, {
"firstName": "Frank",
"lastName": "Peretti",
"genre": "christianfiction"
}],
"musicians": [{
"firstName": "Eric",
"lastName": "Clapton",
"instrument": "guitar"
}, {
"firstName": "Sergei",
"lastName": "Rachmaninoff",
"instrument": "piano"
}]
}
要使程序可以运行必须引入JSON-lib包——org.json.jar包。综合来看,这个JAR包比较好用。
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Test {
public static void main(String[] args) {
String s = "{\"programmers\":[{\"firstName\":\"Brett\",\"lastName\":\"McLaughlin\",\"email\":\"aaaa\"},{\"firstName\":\"Jason\",\"lastName\":\"Hunter\",\"email\":\"bbbb\"},{\"firstName\":\"Elliotte\",\"lastName\":\"Harold\",\"email\":\"cccc\"}]";
JSONObject jsonObject;
JSONArray jsonArray;
try {
jsonObject = new JSONObject(s);
jsonArray = jsonObject.getJSONArray("programmers");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject j = (JSONObject) jsonArray.get(i);
System.out.println(j.get("firstName"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}