我在几分钟内就用PHP解析了一个JSON,这很容易。
我需要在JAVA中做同样的事情并且它更复杂。 我选择了杰克逊。
这里是JSON:
{
"object":"page",
"entry":[
{
"id":"1849584656581184912",
"time":1361458605,
"changes":[
{
"field":"feed",
"value":{
"item":"post",
"verb":"add",
"post_id":"6022322264458251"
}
}
]
},
{
"id":"184965658184912",
"time":1361458606,
"changes":[
{
"field":"feed",
"value":{
"item":"comment",
"verb":"add",
"comment_id":"1849584656581184912_6022322264458251_7510038",
"parent_id":"1849584656581184912_6022322264458251",
"sender_id":657754651107,
"created_time":1361458606
}
},
{
"field":"feed",
"value":{
"item":"comment",
"verb":"add",
"comment_id":"1849584656581184912_6022322264458251_7510037",
"parent_id":"1849584656581184912_6022322264458251",
"sender_id":657754651107,
"created_time":1361458606
}
}
]
}
]
}
这里是PHP代码:
foreach($object["entry"] as $update)
{
// For each entry in notification, display the entry
echo "page id = " . $update["id"];
echo "time = " . $update["time"];
foreach($update["changes"] as $change) {
echo "field = " . $change["field"];
echo "verb = " . $change["value"]["verb"];
if($change["value"]["item"] == "comment") {
echo "Nouveau commentaire publié !";
echo "comment_id = " . $change["value"]["comment_id"];
echo "parent_id = " . $change["value"]["parent_id"];
echo "sender_id = " . $change["value"]["sender_id"];
echo "created_time = " . $change["value"]["created_time"];
} else if($change["value"]["item"] == "post") {
echo "Nouveau post publié !";
echo "post_id = " . $change["value"]["post_id"];
}
}
}
所以我需要相同的东西,解析这个JSON并显示一些信息。
你知道一种简单的方法吗,比如PHP?
由于
答案 0 :(得分:2)
如果您只想直接访问某些字段,则应使用JsonNodes。
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(jsonString);
JsonNode entry = root.get("entry");
…
编辑:请务必查看所有具体的子类。例如,ArrayNode允许您遍历其所有元素。
与演员表相同的代码:
ObjectMapper mapper = new ObjectMapper();
ObjectNode root = (ObjectNode) Jsmapper.readTree(jsonString);
ArrayNode entry = (ArrayNode) root.get("entry");
…