2011-12-05 135 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);