user3840500
user3840500

Reputation: 3

Iterating the JSON object using Java not working exactly

I'm trying to get one JSON object and iterate it. In this case it should iterate only once because I'm having only one complete JSON object, if it has multiple, it should iterate multiple times. But rather it shows the system.out.println string twice. I don't understand whats wrong in this code?

String str = "{\"userId\":\"1234\",\"businessPrimaryInfo\":{\"53bd2a4\":{\"businessSpecificInfo\":{\"businessType\":\"Manufacturing\",\"tradingPlace\":\"Hyderabad\"}},\"53bd2a4e\":{\"businessSpecificInfo\":{\"businessType\":\"Milling\",\"tradingPlace\":\"Mumbai\"}}}}";
JSONObject jsonObj = new JSONObject(str);
Iterator<String> keys = jsonObj.keys();
// Iterate all the users.
while (keys.hasNext()) {
    String key = keys.next();
    try {
    // If the user has Business primary info as JSON object.
    if (jsonObj.has("businessPrimaryInfo")) {
        JSONObject jsonBizPrimaryInfo = jsonObj
            .getJSONObject("businessPrimaryInfo");
        System.out.println("Object is:" + jsonBizPrimaryInfo);

    }
    } finally {

    }

}

Please have a look and let me know where I'm doing wrong.

Upvotes: 0

Views: 48

Answers (1)

Jason
Jason

Reputation: 11832

The two keys that are causing your loop to iterate twice are: userId and businessPrimaryInfo. But you ask the main JSON object if it has a businessPrimaryInfo key. Which it has for every iteration.

What you need to do is check that the current key is businessPrimaryInfo.

Or, you can just ask the primary object if it has a businessPrimaryInfo key, and if so, ask for that child object.

Upvotes: 2

Related Questions