3

I have this JSON object:

{"home_device_name":"light","light_status":[{"id_light":"1","status":"1"},{"id_light":"2","status":"0"}]}

I read it as a JSON object but I can't access "light_status", I want to convert it to an array to be able to read it.

4
  • 1
    If you want to read that in Kotlin, you really should use a Json-parser like Gson or Jackson. Commented Mar 19, 2018 at 8:29
  • Why not get light_status as an json array and iterate through each object and convert them to your desired list manually? Commented Mar 19, 2018 at 8:40
  • light_status is already in readable format. show code how you are reading json Commented Mar 19, 2018 at 8:42
  • It might be silly but why don't you want to use Gson ? Commented Mar 19, 2018 at 9:08

2 Answers 2

2

Use following code :

    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();
    }
Sign up to request clarification or add additional context in comments.

1 Comment

I think he is expecting an answer in Kotlin.
0

First add below model into your project

    class LightStatus {

    var idLight: String? = null
    var status: String? = null

}

Now You can use following code for getting light array

    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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.