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
  • 14,409
  • 18
  • 71
  • 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
  • 3,229
  • 2
  • 21
  • 25
0

Try like below:-

JSONObject root = new JSONObject(body);
String device = root.get("device").toString();
Abhijit Pritam Dutta
  • 5,521
  • 2
  • 11
  • 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
  • 352
  • 1
  • 2
  • 15