2011-12-05 136 views
6

我的JSON字符串具有嵌套值。Java JSON -Jackson-嵌套元素

喜歡的東西

"[{"listed_count":1720,"status":{"retweet_count":78}}]"

我想retweet_count的價值。

我正在使用傑克遜。

下面的代碼輸出「{retweet_count=78}」而不是78。我想知道是否可以通過PHP的方式獲得嵌套值,例如status->retweet_count。謝謝。

import java.io.IOException; 
import java.util.List; 
import java.util.Map; 
import org.codehaus.jackson.map.ObjectMapper; 
import org.codehaus.jackson.type.TypeReference; 

public class tests { 
public static void main(String [] args) throws IOException{ 
    ObjectMapper mapper = new ObjectMapper(); 
    List <Map<String, Object>> fwers = mapper.readValue("[{\"listed_count\":1720,\"status\":{\"retweet_count\":78}}]]", new TypeReference<List <Map<String, Object>>>() {}); 
    System.out.println(fwers.get(0).get("status")); 

    } 
} 
+0

這是可以預料的:'status'的va; ue是一個Map不是嗎?你只需要再次用「retweet_count」來調用'get()'。然而,我同意其中一個建議使用'readTree()'而不是'JsonNode'的方法 - 更容易遍歷。 – StaxMan

回答

9

嘗試類似的東西。如果你使用JsonNode你的生活會更容易。

JsonNode node = mapper.readValue("[{\"listed_count\":1720,\"status\":{\"retweet_count\":78}}]]", JsonNode.class); 

System.out.println(node.findValues("retweet_count").get(0).asInt()); 
2

你或許可以做System.out.println(fwers.get(0).get("status").get("retweet_count"));

編輯1:

變化

List <Map<String, Object>> fwers = mapper.readValue(..., new TypeReference<List <Map<String, Object>>>() {}); 

List<Map<String, Map<String, Object>>> fwers = mapper.readValue(..., new TypeReference<List<Map<String, Map<String, Object>>>>() {}); 

然後做System.out.println(fwers.get(0).get("status").get("retweet_count"));

您沒有地圖對,你有一個地圖<String, Map<String, Object>>對。

編輯2:

好吧我明白了。所以你有一個地圖列表。在列表中的第一張地圖中,您有一個kv對,其中的值是一個整數,另一個kv對的值是另一個地圖。當你說你有一張地圖列表時,它會抱怨,因爲具有int值的kv對不是一張地圖(它只是一個int)。因此,您必須製作所有的kv對映射(將該int更改爲映射),然後使用我上面的編輯。或者你可以使用你的原始代碼,但是當你知道它是一個Map時,將這個Object轉換成一個Map。

那麼試試這個:

Map m = (Map) fwers.get(0).get("status"); 
System.out.println(m.get("retweet_count")); 
+0

我試過這不起作用。 get(「status」)是一個普通對象 – Mob

+1

請參閱我的編輯! –

+0

更多錯誤bro,:'無法反序列化java.util.LinkedHashMap實例超出VALUE_NUMBER_INT標記' – Mob

12

如果你知道你檢索數據的基本結構,是有意義的適當代表它。你得到各種類型的細微安全;)

public static class TweetThingy { 
    public int listed_count; 
    public Status status; 

    public static class Status { 
     public int retweet_count; 
    } 
} 

List<TweetThingy> tt = mapper.readValue(..., new TypeReference<List<TweetThingy>>() {}); 
System.out.println(tt.get(0).status.retweet_count);