Reputation: 113
I'm doing a json parser for java. I receive the json as string and then i try to get all the keys-value
Here is my Json string
{ "Message":{"field": [ {"bit":2,"name":"AAA"}, {"bit":3,"name":"BBB"}]}}
And here is my parser:
JSONObject jObject = new JSONObject(result); //result contains the json
JSONArray info = jObject.getJSONArray("field");
for (int i = 0 ; i < info.length(); i++) {
JSONObject obj = info.getJSONObject(i);
Iterator<String> keys = obj.keys();
while (keys.hasNext()) { //I use key - value cause the json can change
String key = keys.next();
System.out.println("Key: " + key + "\tValue: " + obj.get(key));
}
}
But everytime that i run the code i get:
Error parsing json org.json.JSONException: JSONObject["field"] not found.
And i guess the field its a JsonArray... Am i wrong?
Thank you for your time
Upvotes: 0
Views: 1454
Reputation: 576
try this:
String result = "{ \"Message\":{\"field\": [ {\"bit\":2,\"name\":\"AAA\"}, {\"bit\":3,\"name\":\"BBB\"}]}}";
JSONObject jObject = new JSONObject(result); //result contains the json
JSONArray info = jObject.getJSONObject("Message").getJSONArray("field");
for (int i = 0 ; i < info.length(); i++) {
JSONObject obj = info.getJSONObject(i);
Iterator<String> keys = obj.keys();
while (keys.hasNext()) { //I use key - value cause the json can change
String key = keys.next();
System.out.println("Key: " + key + "\tValue: " + obj.get(key));
}
}
Upvotes: 0
Reputation: 12830
You need to get get JSONArray
field
from JSONObjct
Message
String result = "{ \"Message\":{\"field\": [ {\"bit\":2,\"name\":\"AAA\"}, {\"bit\":3,\"name\":\"BBB\"}]}}";
JSONObject jObject = new JSONObject(result).getJSONObject("Message"); //result contains the json
JSONArray info = jObject.getJSONArray("field");
for (int i = 0 ; i < info.length(); i++) {
JSONObject obj = info.getJSONObject(i);
Iterator<String> keys = obj.keys();
while (keys.hasNext()) { //I use key - value cause the json can change
String key = keys.next();
System.out.println("Key: " + key + "\tValue: " + obj.get(key));
}
}
Output :
Key: name Value: AAA
Key: bit Value: 2
Key: name Value: BBB
Key: bit Value: 3
Upvotes: 2
Reputation: 272
You are one level too deep wanted to get field
from your jObject
.
You need to do :
JSONObject jObject = new JSONObject(result);
JSONObject jMsg = jObject.getJSONObject("Message");
JSONArray info = jMsg.getJSONArray("field");
Upvotes: 2