简体   繁体   English

使用Java中的json简单库解码jsonobject

[英]decoding a jsonobject using json simple library in java

{
"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. 如何解码jsonobject以获得每个键的错误并为每个键分别访问每个值。 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());
            }

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. 目前尚不清楚您的问题sourceLanguage ,但是如果您要一次遍历sourceLanguagemessagearray一次,只需再次重复Iterator逻辑即可。

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. 我不知道你正在使用该库,我认为JSONObject 是,一个 Map ,因为你能打印适用于真正的error JSON拿出来与大家分享过的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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