2013-06-12 62 views
1
{ 
    "files": { 
     "f1.png": { 
      "intext": "A", 
      "inval": 0, 
      "inbinary": false 
     }, 
     "f2.png": { 
      "intext": "A", 
      "inval": 0, 
      "inbinary": true 
     } 
    } 
} 

如何在f1.png值不固定时访问inval的值。即文件的名称可以是任何东西,它不知道,所以我怎样才能使用Java在这个JSON中的各种文件访问值为inval字段?使用java访问嵌套的JSON对象值

+0

您确定您的意思是Java? – NimChimpsky

+1

有JSON库可以做到这一点。 – NINCOMPOOP

回答

1

请尝试以下代码,

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

希望它能解决您的问题

+0

它对我很好。谢谢 :) – user2436651

0

使用JacksonJsonNode,你会怎么做:

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<Map.Entry<String, JsonNode>> iterator = filesNode.fields(); 
Map.Entry<String, JsonNode> entry; 
while (iterator.hasNext()) { 
    entry = iterator.next(); 
    // the "inval" field is entry.getValue().get("inval") 
} 

如果你可以使用这个this project变得更加简单:

// or .fromFile(), .fromReader(), others 
final JsonNode node = JsonLoader.fromString(whatever); 

final Map<String, JsonNode> map = JacksonUtils.nodeToMap(node.get("files")); 
// walk the map 
0

嵌套阵列型,

{ 
"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<String> comboList = new ArrayList<String>(); 
     for(int i=0;i<list.length();i++){ 
      JSONObject jsonObject = (JSONObject)list.get(i); 
      if(jsonObject==null) 
       continue; 
      comboList.add((String)jsonObject.get("fields")); 
     } 
    }