1.JSON是什么
传递对象的语法,对象可以是String,int,数组等等,结构一般为键值对例如{“name”:”小明”,”age”,16}建必须是String类型,值可以是int,String,数组等等
2.JSON有哪两种结构
1.JSONObject
单个的json,用大括号包裹,一般有三种
{“name”:”小明”}只有一个属性
{“name”:”小明”,”age”,16}有多个属性
{“name”:”小明”,”info”,{“sex”:”男”,”age”,16}}嵌套了JSONObject
2.JSONArray
JSONObject数组,例如:
[{“name”:”小明”,”age”,16},{“name”:”小合”,”age”,12}]
外面包一层值中括号
3.如何解析JSONObject(案例)
{“name”:”小明”,”age”,16}其中小明,和16分别赋值到两个TextView中
//\是标记符,使name不会被识别为String而是一种标签
String json_str="{\"name\":\"小明\",\"age\":21}";
try {
//把{"name":"小明","age",16}传递给JSONObject
JSONObject mjsonObject = new JSONObject(json_str);
//读取JSONObject里的属性
String name=mjsonObject.getString("name");
String age=mjsonObject.getInt("age")+"";
JSONObject class_json=mjsonObject.getJSONObject("info");
main_tv.setText(name);
main_tv2.setText(age);
} catch (JSONException e) {
e.printStackTrace();
}
4.如何解析JSONArray(案例)
[{“name”:”小明”,”age”,16},{“name”:”小合”,”age”,12}]其中小明,16,小合,12分别赋值到四个TextView中
String json_str="[ {\"name\":\"小明\",\"age\":16}, {\"name\":\"小合\",\"age\":12}]";
try {
JSONArray jsonArray=new JSONArray(json_str);
JSONObject obj1=jsonArray.getJSONObject(0);
demo6_tv.setText(obj1.getString("name"));
demo6_tv2.setText(obj1.getInt("age")+"");
JSONObject obj2=jsonArray.getJSONObject(1);
demo6_tv3.setText(obj2.getString("name"));
demo6_tv4.setText(obj2.getInt("age")+"");
} catch (JSONException e) {
e.printStackTrace();
}