vbNewbie
vbNewbie

Reputation: 3345

parse json object from json array in java using com.fasterxml.jackson.databind.JsonNode;

I am trying to parse some json which is a groupd of objects within an array. I am not fluent with java and having a hard time figuring out how to do this.

    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);

the json format:

  {
  "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"
 }
 }

This is the json from the facebook graph api. I also need to extract the cursors and links below so would they also appear as one of the objects.

Appreciate advice.

Thanks

Upvotes: 0

Views: 1684

Answers (1)

StaxMan
StaxMan

Reputation: 116502

I think the real question is what you are trying to achieve? You are already parsing JSON into a tree model (JsonNode), and from that point on you can traverse content freely, using methods get, path and at (which uses JSON Pointer expression).

Or, as suggested by Samwise above, could consider modeling Java classes with same structure as JSON, so that you would have even easier time accessing data as regular Java objects. If so, you'd parse it simply by:

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

Upvotes: 1

Related Questions