赞
踩
对象在js中表示为“{}”括起来的内容,数据结构为 {key:value,key:value,…}的键值对的结构,在面向对象的语言中,key为对象的属性,value为对应的属性值,所以很容易理解,取值方法为 对象.key 获取属性值,这个属性值的类型可以是 数字、字符串、数组、对象几种
例子:
1.{"name":"张三","age":21}
2.{"name":"张三","age":21,"info":{"class":"三年一班","id":2016001}}
数组在js中是中括号“[]”括起来的内容,数据结构为 [“java”,”javascript”,”vb”,…],取值方式和所有语言中一样,使用索引获取,字段值的类型可以是 数字、字符串、数组、对象几种:
例子:
1.[{"name":"Mr Jiang"},{"identity":"teacher"}]
2.[ {"name":"张三","age":21,"info":{"class":"三年一班","id":2016001}}, {"name":"李四","age":22,"info":{"class":"三年二班","id":2016002}}]
3.[{"name":"pelon"},{"infor":{"class":"lenovo1602","num":{"hen":3,"zhong":3}}}]
JSON的数据解析案例1(JSONArray);
JSON数据如下:
String Json_str3="[ {\"name\":\"张三\",\"age\":21,\"info\":{\"class\":\"三年一班\",\"id\":2016001}}, {\"name\":\"李四\",\"age\":22,\"info\":{\"class\":\"三年二班\",\"id\":2016002}}]\n";
可将JSON数据放入https://www.json.cn/中查看:
解析过程:
private void parseJson() {
String Json_str3="[ {\"name\":\"张三\",\"age\":21,\"info\":{\"class\":\"三年一班\",\"id\":2016001}}, {\"name\":\"李四\",\"age\":22,\"info\":{\"class\":\"三年二班\",\"id\":2016002}}]\n";
try {
//该JSON数据是JSONArray数组所以需要创建JsonArray对象,并将字符串传入
JSONArray jsonArray3=new JSONArray(Json_str3);
JSONObject jsonObject31=jsonArray3.getJSONObject(0);
String name1=jsonObject31.getString("name");
int age1=jsonObject31.getInt("age");
JSONObject jsonObject311=jsonObject31.getJSONObject("info");
String class1=jsonObject311.getString("class");
int id1=jsonObject311.getInt("id");
JSONObject jsonObject32=jsonArray3.getJSONObject(1);
String name2=jsonObject32.getString("name");
int age2=jsonObject32.getInt("age");
JSONObject jsonObject321=jsonObject32.getJSONObject("info");
String calss2=jsonObject321.getString("class");
int id2=jsonObject321.getInt("id");
t1.setText("姓名:"+name1);
t2.setText("年龄:"+age1);
t3.setText("班级:"+class1);
t4.setText("id:"+id1);
t5.setText("姓名:"+name2);
t6.setText("年龄:"+age2);
t7.setText("班级:"+calss2);
t8.setText("id:"+id2);
} catch (JSONException e) {
e.printStackTrace();
}
}

运行截图:
JSON的数据解析案例2(JSONObject):
解析的数据对象:
String json_str=" {\"name\":\"张三\",\"age\":21}";
同样的,将JSON数据放入https://www.json.cn/中查看:
过程:
private void parseJson() {
String json_str=" {\"name\":\"张三\",\"age\":21}";
try {
//创建JSONObject对象
JSONObject jsonObject=new JSONObject(json_str);
String name=jsonObject.getString("name");
int age=jsonObject.getInt("age");
t1.setText("姓名:"+name);
t2.setText("年龄:"+age);
} catch (JSONException e) {
e.printStackTrace();
}
}

结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。