2014-11-14 65 views
0

我想解析一些數組中的對象json。我不熟悉java,很難搞清楚如何做到這一點。使用com.fasterxml.jackson.databind.JsonNode解析json數組中的json對象;

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。我還需要提取下面的遊標和鏈接,以便它們也可以作爲其中一個對象出現。

欣賞建議。

謝謝

+1

只是爲了你爲什麼不使用傑克遜直接映射,即創建一個類似於您的JSON結構的POJO,只是使用ObjectMapper.convertValue我的知識? – 2014-11-14 18:24:44

回答

1

我認爲真正的問題是你想要實現的嗎?您已經將JSON解析爲樹模型(JsonNode),並且從這一點開始,您可以使用方法getpathat(它使用JSON指針表達式)自由遍歷內容。

或者,如上面Samwise所建議的那樣,可以考慮對與JSON具有相同結構的Java類進行建模,以便您可以更輕鬆地以常規Java對象的形式訪問數據。如果是的話,你會簡單地分析它:

Graph graph = mapper.readValue(post); 
Data d = graph.getData().get(0); // for first entry in "data" List