0
{
"module": "abc",
"chapter": "1",
"source": "Google",
"error": {
    "1": {
        "sourceLanguage": "English",
        "message": "not found",
        "array": "[a, b, c]"
    },
    "2": {
        "sourceLanguage": "English",
        "message": "not found",
        "array": "[a, b, c]"
    },
    "3": {
        "sourceLanguage": "English",
        "message": "not found",
        "array": "[l, m, n]"
    }    
 }
}    

how to decode jsonobject to get error with each key & access each value separately for each key. Tried this but cannot split value of each key.

Map mapobj=(JSONObject) jsonObj.get("error");
            Iterator iterator=mapobj.entrySet().iterator();
            while(iterator.hasNext()){
                Map.Entry pair=(Entry) iterator.next();
                System.out.println(pair.getKey()+""+pair.getValue());
            }
Grishma Oswal
  • 303
  • 1
  • 7
  • 22
  • What do you mean by _Tried this but cannot split value of each key_. Your `pair.getValue()` will return a `JSONObject`. How do you want to print it? – Codebender Jul 07 '15 at 08:09
  • i want to write to csv the value returned – Grishma Oswal Jul 07 '15 at 08:30
  • I'm don't think this works. Try castig with Map propertyMap = JacksonUtils.fromJSON(properties, Map.class); – Razvan Manolescu Jul 07 '15 at 08:31
  • @GrishmaOswal, your problem is still not clear... What is your print statement printing now.. And how do you want it to print instead... Update the question with this information. Also check Ravi's answer if it suits you... – Codebender Jul 07 '15 at 08:35

1 Answers1

0

It's unclear exactly what your issue here is but if you meant to iterate over the sourceLanguage, message and array one at a time, just repeat your Iterator logic once again.

Map mapobj = (JSONObject) jsonObj.get("error");
Iterator iterator = mapobj.entrySet().iterator();

while(iterator.hasNext()){
    Map.Entry pair = (Entry) iterator.next();
    System.out.println(pair.getKey() + "" + pair.getValue());

    Map errorObj = new JSONObject(pair.getValue());
    Iterator errorIterator = errorObj.entrySet().iterator();

    while(errorIterator.hasNext()) {
        Map.Entry errPair = (Entry) errorIterator.next();
        System.out.println(errPair.getKey() + "" + errPair.getValue());
    }
}

I'm not sure which library you're working with and I've assumed that JSONObject is-a Map holds true for that since you're able to print the error json out with the code you've shared.

Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89