2017-05-08 153 views
-2

我可以知道如何从json数组中获取JSON对象吗?从json数组中获取对象

JSON:

[ 
{ 
"id": 1, 
"region": "Ilocos Region (Region I)", 
"province": "Ilocos Norte", 
"city": "Laoag City" 
}, 
{ 
"id": 2, 
"region": "Ilocos Region (Region I)", 
"province": "Ilocos Norte", 
"city": "Batac City" 
}, 
{ 
"id": 3, 
"region": "Ilocos Region (Region I)", 
"province": "Ilocos Sur", 
"city": "Vigan City" 
} 
] 

我可以得到该地区,省,市,但我不能得到的ID。

这里是我使用的代码:

try { 
        br = new BufferedReader(new FileReader(path+"json/src_city.json")); 
        try { 
         while ((inputline = br.readLine()) != null) { 

           JSONArray a = (JSONArray) parser.parse(inputline); 
           for (Object o : a) { 
            JSONObject sample = (JSONObject) o;   

            id = (int) sample.get("id"); 
}} 
+0

我找到了我的问题的答案,它被解释得很好。 http://stackoverflow.com/a/31194430/1840521 – LyodMichael

回答

0

如果你能得到的区域,可能是这个原因是id为int,你不能用这样的方式获得:ID =( int)sample.get(“id”);

+0

嗨,我可以得到区域通过使用字符串值,因为ID是INT我使用INT,我也无法获得ID即使我使用字符串。 – LyodMichael

+0

欢迎来到SO。使用代码格式(请参阅答案窗口中的“帮助”)将使您的答案更具可读性。 – Gary99

0

我觉得杰森只使用字符串值,尝试围绕报价数量:

{ 
"id": "1", 
"region": "Ilocos Region (Region I)", 
"province": "Ilocos Norte", 
"city": "Laoag City" 
}, 

然后你可以检索出来的对象

id = Integer.valueOf(sample.get("id")); 
0

我们可以以后解析回整从json数组中获取每个jsonnode,如下所示。而jsonnode也提供了解析整数的方法。

if (a.isArray()) { 
    for (final JsonNode objNode : a) { 
     id = objNode.get("id").asInt(); 
    } 
}