I have the following JSONArray:
[
{
"Lng":17.908817,
"name":"S1",
"id":1,
"sensor:":[
"Temperature",
"Wind"
],
"Lat":47.089492
},
{
"Lng":17.908458,
"name":"S2",
"id":2,
"sensor:":[
"Temperature",
"Wind",
"Humidity"
],
"Lat":47.089246
},
{
"Lng":17.908222,
"name":"S3",
"id":3,
"sensor:":[
"Wind"
],
"Lat":47.089662
}
]
I can split it to JSONObject but if I try to split the Object it returns null.
My code:
Object object = JSONValue.parse(result);
JSONArray array = (JSONArray)object;
for(int i = 0 ; i < array.size(); i++){
System.out.println(array.get(i));
JSONObject jsonObject = (JSONObject)array.get(i);
for(int j = 0 ; j < jsonObject.size(); j++){
System.out.println(jsonObject.get(j));
}
}
Result:
{"Lng":17.908817,"name":"S1","sensor:":["Temperature","Wind"],"id":1,"Lat":47.089492}
null
null
null
null
null
{"Lng":17.908458,"name":"S2","sensor:":["Temperature","Wind","Humidity"],"id":2,"Lat":47.089246}
null
null
null
null
null
{"Lng":17.908222,"name":"S3","sensor:":["Wind"],"id":3,"Lat":47.089662}
null
null
null
null
null
gkrls
2,6642 gold badges17 silver badges30 bronze badges
3 Answers 3
A JSONObject (a JSON object) is not indexable. Elements are unordered. What you are trying to do
System.out.println(jsonObject.get(j));
doesn't make sense. Access name-value pairs through their names.
answered Aug 27, 2014 at 15:45
Sotirios Delimanolis
281k62 gold badges718 silver badges744 bronze badges
Sign up to request clarification or add additional context in comments.
6 Comments
Sotirios Delimanolis
@user3768431 The array has the name
sensor, so you can access it with jsonObject.get("sensor").Duncan
I realized after i post the question.
Duncan
One more and I let it. What is the proper way? I tried this: JSONArray array2 = (JSONArray)jsonObject.get("sensor"); but it isnt working.
Sotirios Delimanolis
@user Which library are you using? I might have gotten them wrong. Also, what does is not working mean? Does it throw an exception? Does it return
null?Sotirios Delimanolis
@us Oh, there's a
: at the end of sensor. |
You can use:
Iterator<?> keys = jsonObject.keys();
while( keys.hasNext() ){
String key = (String)keys.next();
// use jsonObject.get(key)
}
instead of that "j".
answered Aug 27, 2014 at 15:48
ROMANIA_engineer
57.1k30 gold badges211 silver badges207 bronze badges
Comments
Try to access the JSONObject properties through their keys:
JSONArray array = JSONValue.parse(result);
for(int i = 0 ; i < array.size(); i++)
{
System.out.println(array.get(i));
JSONObject jsonObject = (JSONObject) array.get(i);
int id = jsonObject.getInt("id");
String lng = jsonObject.getString("Lng");
String lat = jsonObject.getString("Lat");
Object sensor = jsonObject.getString("sensor");
String name = jsonObject.getString("name");
System.out.println(id);
System.out.println(name);
System.out.println(sensor);
System.out.println(lat);
System.out.println(lon);
}
answered Aug 27, 2014 at 15:58
tmarwen
16.5k5 gold badges48 silver badges65 bronze badges
Comments
lang-java