Java JSON -Jackson-嵌套元素

我的JSON字符串具有嵌套值。

就像是

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

我想要retweet_count的值。

我正在使用jackson。

下面的代码输出“ {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> fwers = mapper.readValue("[{\"listed_count\":1720,\"status\":{\"retweet_count\":78}}]]", new TypeReference<List <Map>>() {}); System.out.println(fwers.get(0).get("status")); } } 

尝试类似的东西。 如果你使用JsonNode,你的生活会更容易。

 JsonNode node = mapper.readValue("[{\"listed_count\":1720,\"status\":{\"retweet_count\":78}}]]", JsonNode.class); System.out.println(node.findValues("retweet_count").get(0).asInt()); 

如果您知道要检索的数据的基本结构,那么正确表示它是有意义的。 你会得到类型安全等各种细节;)

 public static class TweetThingy { public int listed_count; public Status status; public static class Status { public int retweet_count; } } List tt = mapper.readValue(..., new TypeReference>() {}); System.out.println(tt.get(0).status.retweet_count); 

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

编辑1:

更改

 List > fwers = mapper.readValue(..., new TypeReference>>() {}); 

 List>> fwers = mapper.readValue(..., new TypeReference>>>() {}); 

然后执行System.out.println(fwers.get(0).get("status").get("retweet_count"));

你没有对的Map,你有一个>对的>

编辑2:

好吧,我明白了。 所以你有一张地图清单。 在列表的第一个映射中,您有一个kv对,其中值是一个整数,另一个kv对,其中值是另一个映射。 当你说你有一张地图的地图列表时,它会抱怨,因为带有int值的kv对不是一个map(它只是一个int)。 因此,您必须制作所有kv对映射(将该int更改为映射),然后使用上面的编辑。 或者您可以使用原始代码,但在您知道它是地图时将对象强制转换为地图。

所以试试这个:

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