0

How can I get the value of device (SE_S2) or status using JSONObject class?

String body = '{"device":"SE_S2","status":"1","time":"1524737618.66301","status":"ON"} '
JSONObject root = new JSONObject(body);
Ascalonian
  • 13,791
  • 18
  • 70
  • 103
Andrea
  • 35
  • 1
  • 4

3 Answers3

1

It won't work, because you have a duplicate key ("status"). If you remove that, you'd be able to get the device by doing:

String body = "{\"device\":\"SE_S2\",\"status\":\"1\",\"time\":\"1524737618.66301\"}";
JSONObject root = new JSONObject(body);
System.out.println(root.get("device"));
Magd Kudama
  • 2,747
  • 1
  • 17
  • 23
0

Try like below:-

JSONObject root = new JSONObject(body);
String device = root.get("device").toString();
Abhijit Pritam Dutta
  • 5,284
  • 2
  • 8
  • 17
0

For json {\"device\":\"SE_S2\",\"status\":\"1\",\"time\":\"1524737618.66301\"}

  1. To get "SE_S2" you can use root.get("device")
  2. To get "1" you can use root.get("status")

Note that you have multiple element with the same key 'status' which is not allowed.

pranay jain
  • 302
  • 2
  • 12