我试图解析一些json,它是数组中的一组对象。我不熟悉java并且很难弄清楚如何做到这一点。
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
JsonNode messageNode = mapper.readTree(post);
if (!messageNode.isArray()){
try {
throw new Exception("INVALID JSON");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ArrayList<String> listObjects = null;
JsonParser parser = mapper.getFactory().createParser(post);
json格式:
{
"data": [
{
"id": "897569693587466_897626706915098",
"from": {
"id": "1809583315",
"name": "Lena Cann Jordan"
},
"message": "Amen.",
"can_remove": false,
"created_time": "2014-11-11T22:41:11+0000",
"like_count": 0,
"user_likes": false
},
{
"id": "897569693587466_897627376915031",
"from": {
"id": "1776031725",
"name": "Kyla Munford"
},
"message": "Tell me what my God can't do!!!",
"can_remove": false,
"created_time": "2014-11-11T22:42:51+0000",
"like_count": 0,
"user_likes": false
},
{
"id": "897569693587466_897631636914605",
"from": {
"id": "100000106496788",
"name": "Sarah Barklow Tyson"
},
"message": "That's bc God is awesome!! He can give or take away!! \ud83d\ude4f\u2795",
"can_remove": false,
"created_time": "2014-11-11T22:49:46+0000",
"like_count": 0,
"user_likes": false
}
],
"paging": {
"cursors": {
"after": "WTI5dGJXVnVkRjlqZFhKemIzSTZPRGszTmpVMk1USXdNalExTkRrd09qRTBNVFUzTkRrNU5qTTZOREE9",
"before": "WTI5dGJXVnVkRjlqZFhKemIzSTZPRGszTmpJMk56QTJPVEUxTURrNE9qRTBNVFUzTkRVMk56RTZNelU9"
},
"previous": "some link"
}
}
这是来自facebook图api的json。我还需要提取下面的游标和链接,这样它们也会显示为其中一个对象。
欣赏建议。
由于
答案 0 :(得分:1)
我认为真正的问题是你想要实现的目标?您已经将JSON解析为树模型(JsonNode
),从那时起,您可以使用方法get
,path
和at
(使用方法)自由遍历内容JSON指针表达式)。
或者,正如上面Samwise所建议的那样,可以考虑使用与JSON相同的结构来构建Java类,这样您就可以更轻松地将数据作为常规Java对象访问。如果是这样,您只需通过以下方式解析它:
Graph graph = mapper.readValue(post);
Data d = graph.getData().get(0); // for first entry in "data" List