mducc
mducc

Reputation: 743

How to convert JSON to array without using Gson

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.

Upvotes: 3

Views: 826

Answers (2)

Vinayak B
Vinayak B

Reputation: 4520

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
}

Upvotes: 0

NehaK
NehaK

Reputation: 2737

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();
    }

Upvotes: 2

Related Questions