1.JSON是什么
JSON 是一种轻量级的数据格式,他基于 javascript 语法的子集,即数组和对象表示。
2.JSON有哪两种结构
数组和对象
数组是用一对方括号括起一组用逗号隔开的 javascript 值
var aNames=["hello", 12, true , null];
对象是通过两个花括号来定义的。在花括号内可以放置任意数量的“名称-值”对,定义格 式字符串值”。
var oCar = {
"color": "red",
"doors" : 4,
"paidFor" : true
};
3.如何解析JSONObject(附案例)
String json_str="{\"name\":\"张三\",\"age\":21,\"info\":{\"class\":\"三年一班\",\"id\":2016001}}\n";
try {
////创建JSONObject对象,存入json_str
JSONObject jsonObject=new JSONObject(json_str);
String name=jsonObject.getString("name");
int age=jsonObject.getInt("age");
tv1.setText(name);
tv2.setText(age+"");
//创建JSONOBject新对象,得到嵌套JSON
JSONObject classObject=jsonObject.getJSONObject("info");
String classname=classObject.getString("class");
int id=classObject.getInt("id");
tv3.setText(classname);
tv4.setText(id+"");
} catch (JSONException e) {
e.printStackTrace();
}
3.如何解析JSONArray(附案例)
String json_str="[ {\"name\":\"张三\",\"age\":21}, {\"name\":\"赵四\",\"age\":22}]\n";
try {
//创建JSONArray对象,存入json_str
JSONArray jsonArray=new JSONArray(json_str);
//创建JSONObject对象,得到数组第一个
JSONObject obj1=jsonArray.getJSONObject(0);
String name=obj1.getString("name");
tv1.setText(name);
//创建JSONObject对象,得到数组第二个
JSONObject obj2=jsonArray.getJSONObject(1);
int age=obj2.getInt("age");
tv2.setText(age+"");
} catch (JSONException e) {
e.printStackTrace();
}