简体   繁体   中英

java Error parsing JsonObject

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

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");

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM