KaustubhK
KaustubhK

Reputation: 775

how do i convert list of jsonNodes to single jsonNode

I am using Jackson library. I have number of java objects which are nothing but the wrapper for jsonNode. So want to convert these list of jsonNodes into single jsonNode. how can i do that. i tried this

   public JsonNode converter(List<? extends Base> objList){
    List<String> jsonList=new ArrayList<String>();
    try
     {
    for (Base raObject : objList) {
        ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        String json = ow.writeValueAsString(raObject);
        jsonList.add(json);
    }
     return JsonHelper.convert(jsonList); 
    }catch(Exception e)
    {
         System.out.println("Error occured while converting objectlist to jsonNode::"+e);
         return null;
    }       
}

this is not working. ithere any other way?

Upvotes: 3

Views: 3489

Answers (1)

araqnid
araqnid

Reputation: 133522

If each of your objects can be serialized, then you should also be able to serialize a list of them to combine them into a json list:

mapper.writeValueAsString(objList); // produces a JSON list: "[ obj1, obj2 ...]"

You can also ask Jackson to simply convert the objList to an ArrayNode instead:

ArrayNode arrayNode = mapper.convertValue(objList, ArrayNode.class);

But if you actually had a method in Base to allow conversion to a JsonNode, you could simply build ArrayNode yourself:

ArrayNode arrayNode = mapper.getNodeFactory().arrayNode();
for (Base obj : objList) {
    arrayNode.add(obj.toJsonNode());
}

This would avoid round-tripping via a JSON representation.

Upvotes: 2

Related Questions