JSON
- JSON是什么
- 如何解析JSONObject
- 如何解析JSONArray
JSON是什么
JSON(javaScript Object Notation)是一种轻量级的数据交换格式。
JSON有两种数据结构:
单条JSON数据,Android中称之为JSONObject.
多条JSON组合,Android中称之为JSONArray.
如何解析JSONObject
{“name”:”张三”,”age”:21}
private void parseJson() {
String json_str = "{\"name\":\"张三\",\"age\":21}";
try {
JSONObject mJsonObject = new JSONObject(json_str);
String name = mJsonObject.getString("name");
int age = mJsonObject.getInt("age");
tv1.setText(name + age + "");
} catch (JSONException e) {
e.printStackTrace();
}
}
如何解析JSONArray
{“name”:”张三”,”age”:21,”info”:{“class”:”三年一班”,”id”:2016001}}
private void parseJson1() {
String json_str = "{\"name\":\"张三\",\"age\":21,\"info\":{\"class\":\"三年一班\",\"id\":2016001}}\n";
try {
JSONObject jsonObject = new JSONObject(json_str);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
JSONObject classObj = jsonObject.getJSONObject("info");
String className = classObj.getString("class");
int id = classObj.getInt("id");
tv2.setText(name + " " + age + className + "" + " " + id + "");
} catch (JSONException e) {
e.printStackTrace();
}
}