0

我已经在几分钟内解析了一个 JSON 到 PHP,这很容易。

我需要在 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 中吗?

谢谢

4

1 回答 1

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");
…
于 2013-02-22T09:34:00.227 回答