JSON的基本数据格式有这几种:
1.一个JSON对象——JSONObject
{"name":"胡小威" , "age":20 , "male":true}
答、直接解析
JSONObject jsonObject = new JSONObject(json);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
boolean male = jsonObject.getBoolean("male");
2.一个JSON数组——JSONArray
[{"name":"胡小威" , "age":20 , "male":true},{"name":"赵小亮" , "age":22 , "male":false}]
答、先解析成数组,再一个个解析
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
boolean male = jsonObject.getBoolean("male");
3.复杂一点的JSONObject
{"name":"胡小威", "age"=20, "male":true, "address":{"street":"岳麓山南", "city":"长沙","country":"中国"}}
答、 先解析成json,再解析得到的json
JSONObject jsonObject = new JSONObject(json);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
boolean male = jsonObject.getBoolean("male");
JSONObject addressJSON = jsonObject.getJSONObject("address");
String street = addressJSON.getString("street");
String city = addressJSON.getString("city");
String country = addressJSON.getString("country");
Address address = new Address(street, city, country);
Person person = new Person(name, age, male, address);
4.复杂一点的JSONArray
[
{"name":"胡小威", "age"=20, "male":true, "address":{"street":"岳麓山南", "city":"长沙","country":"中国"}},
name":"赵小亮", "age"=22, "male":false, "address":{"street":"九州港", "city":"珠海","country":"中国"}}
]
答:写解析成数组,再解析成得到的json, 解析后得到json继续解析
jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
boolean male = jsonObject.getBoolean("male");
JSONObject addressJSON = jsonObject.getJSONObject("address");
String street = addressJSON.getString("street");
String city = addressJSON.getString("city");
String country = addressJSON.getString("country");