使用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字段的值?

请尝试下面的代码,

 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(); } 

希望它能解决你的问题

使用Jackson和JsonNode ,您可以:

 private static final ObjectReader READER = new ObjectMapper() .getReader; // blah // read the node final JsonNode node = READER.readTree(fromWhatever); // access the inner "files" member final JsonNode filesNode = node.get("files"); 

访问内部对象。

然后走你要做的filesNode对象:

 final Iterator> iterator = filesNode.fields(); Map.Entry entry; while (iterator.hasNext()) { entry = iterator.next(); // the "inval" field is entry.getValue().get("inval") } 

如果您可以使用此项目,这将变得更加简单:

 // or .fromFile(), .fromReader(), others final JsonNode node = JsonLoader.fromString(whatever); final Map map = JacksonUtils.nodeToMap(node.get("files")); // walk the map 

您可以使用JsonPath库来访问子元素。 https://github.com/json-path/JsonPath

它可以很简单

 List names = JsonPath.read(json, "$.files.*); 

经过一些修改。

对于嵌套数组类型,

 { "combo": [ {"field":"divisions"}, {"field":"lob"} ] 

下面的代码将有所帮助。

 Iterator keys = jsnObj.keys(); while(keys.hasNext()) { String key = (String) keys.next(); JSONArray list = (JSONArray) jsnObj.get(key); if(list==null || list.length()==0) return null; List comboList = new ArrayList(); for(int i=0;i