android解析JSON数据

2019-12-10 18:41:46王旭
本文给大家介绍的是在Android中解析json数据的方法的几种方法,非常的简单实用,有需要的小伙伴可以参考下  

JSONObject的使用

 一、 JSON对象的使用:

String content = "{'username': 'linux', 'password': '123456'}";
JSONObject jsonObject = new JSONObject(content);
String username = jsonObject.getString("username");
String password = jsonObject.getString("password");

 

二、 JSON数组的使用:

String jsonContent = "[{'user': '刘力', 'age': 21, 'femal': true}, "
            + "{'user': 'chen', 'age': 20, 'femal': false}]";
JSONArray jsonArray = new JSONArray(jsonContent);
for (int i = 0; i < jsonArray.length(); i++) {
   JSONObject object = jsonArray.getJSONObject(i);
   System.out.print(object.getString("user") + " ");
   System.out.print(object.getInt("age") + " ");
   System.out.print(object.getBoolean("femal") + " ");
   System.out.println();
}

三、 JSON数组与JSON对象混合使用

String jsonString = "[{'user': 'tomhu', 'age': 21, " + "'info': {'adress': 'hubai', 'sex': 'femal'}}, "
          + "{'user': 'chen', 'age': 20, " + "'info': {'adress': 'hunan', 'sex': 'male'}}]";
JSONArray jsonArrays = new JSONArray(jsonString);
for (int i = 0; i < jsonArrays.length(); i++) {
  JSONObject objects = jsonArrays.getJSONObject(i);
  System.out.print(objects.getString("user") + " ");
  System.out.print(objects.getInt("age") + " ");
  System.out.print(objects.getJSONObject("info").getString("adress") + " ");
  System.out.print(objects.getJSONObject("info").getString("sex") + " ");
  System.out.println();
}