我有这个JSON对象:
{"home_device_name":"light","light_status":[{"id_light":"1","status":"1"},{"id_light":"2","status":"0"}]}
我将其作为JSON对象读取但我无法访问“light_status”,我想将其转换为数组以便能够读取它。
答案 0 :(得分:2)
使用以下代码:
String str = "{\"home_device_name\":\"light\",\"light_status\":[{\"id_light\":\"1\",\"status\":\"1\"},{\"id_light\":\"2\",\"status\":\"0\"}]}";
try {
JSONObject jsonObject = new JSONObject(str);
String home_device_name = jsonObject.getString("home_device_name");
JSONArray jsonArray = jsonObject.getJSONArray("light_status");
for (int i = 0; i < jsonArray.length(); i++) {
String id_light = jsonArray.getJSONObject(i).getString("id_light");
String status = jsonArray.getJSONObject(i).getString("status");
Log.d("Value", "Pos = " + i + " id_light = " + id_light + " status = " + status);
}
} catch (JSONException e) {
e.printStackTrace();
}
答案 1 :(得分:-1)
首先将以下模型添加到您的项目中
class LightStatus {
var idLight: String? = null
var status: String? = null
}
现在您可以使用以下代码获取光阵列
fun getLightArray() :ArrayList<LightStatus>{
val jsonString = "{\"home_device_name\":\"light\",\"light_status\":[{\"id_light\":\"1\",\"status\":\"1\"},{\"id_light\":\"2\",\"status\":\"0\"}]}";
val jsonObject=JSONObject(jsonString)
val jsonArray =jsonObject.getJSONArray("light_status")
val lightArray =ArrayList<LightStatus>()
for (i in 0..jsonArray.length()-1){
val lightStatus=LightStatus()
lightStatus.idLight=jsonArray.getJSONObject(i).getString("id_light")
lightStatus.status=jsonArray.getJSONObject(i).getString("status")
lightArray.add(lightStatus)
}
return lightArray
}