使用Java访问嵌套的JSON对象值 [英] Access nested JSON object value using java
本文介绍了使用Java访问嵌套的JSON对象值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
{
"files": {
"f1.png": {
"intext": "A",
"inval": 0,
"inbinary": false
},
"f2.png": {
"intext": "A",
"inval": 0,
"inbinary": true
}
}
}
当f1.png值不固定时如何访问inval值.即文件名可以是任何名称,尚不知道,所以我如何使用Java访问该JSON中各种文件的inval字段值?
How to access value of inval when the f1.png value is not fixed. i.e. the name of file can be anything, its not known so how can I access value for inval field for various files in this JSON using Java?
推荐答案
请尝试以下代码,
import org.json.JSONException;
import org.json.JSONObject;
public static void main(String[] args) {
String jsonString = "{\"files\": {\"f1.png\": {\"intext\": \"A\",\"inval\": 0,\"inbinary\": false}, \"f2.png\": {\"intext\": \"A\",\"inval\": 0,\"inbinary\": true}}}";
try {
JSONObject jsonObject =new JSONObject(jsonString);
JSONObject jsonChildObject = (JSONObject)jsonObject.get("files");
Iterator iterator = jsonChildObject.keys();
String key = null;
while(iterator.hasNext()){
key = (String)iterator.next();
System.out.println("inval value: "+((JSONObject)jsonChildObject.get(key)).get("inval"));
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
希望它可以解决您的问题
Hope it solves your issue
这篇关于使用Java访问嵌套的JSON对象值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文