Iterate through JSONObject from root in json simple

一个人想着一个人 提交于 2019-12-03 04:52:39

问题


I am trying to iterate over a json object using json simple. I have seen answers where you can do a getJSONObject("child") from

{ "child": { "something": "value", "something2": "value" } }

but what if I just have something

{
"k1":"v1",
"k2":"v2",
"k3":"v3"
} 

and want to iterate over that json object. This:

Iterator iter = jObj.keys();

throws: cannot find symbol symbol : method keys() location: class org.json.simple.JSONObject


回答1:


Assuming your JSON object is saved in a file "simple.json", you can iterate over the attribute-value pairs as follows:

JSONParser parser = new JSONParser();

Object obj = parser.parse(new FileReader("simple.json"));

JSONObject jsonObject = (JSONObject) obj;

for(Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
    String key = (String) iterator.next();
    System.out.println(jsonObject.get(key));
}



回答2:


You can do like this

String jsonstring = "{ \"child\": { \"something\": \"value\", \"something2\": \"value\" } }";
JSONObject resobj = new JSONObject(jsonstring);
Iterator<?> keys = resobj.keys().iterator();
while(keys.hasNext() ) {
    String key = (String)keys.next();
    if ( resobj.get(key) instanceof JSONObject ) {
        JSONObject xx = new JSONObject(resobj.get(key).toString());
        Log.d("res1",xx.getString("something"));
        Log.d("res2",xx.getString("something2"));
    }
}



回答3:


In Java 8 we can use lambdas

void handleJSONObject(JSONObject jsonObject) {
jsonObject.keys().forEachRemaining(key -> {
    Object value = jsonObject.get(key);
    logger.info("Key: {0}\tValue: {1}", key, value);
  }
}


来源:https://stackoverflow.com/questions/24371957/iterate-through-jsonobject-from-root-in-json-simple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!