Wednesday, 28 October 2015

Jackson Create JSON Using Tree Model

By using ObjectNode, we can prepare JSON document on the fly.

Step 1: Define JsonNodeFactory, ObjectMapper classes.
JsonNodeFactory factory = new JsonNodeFactory(false);
ObjectMapper mapper = new ObjectMapper();

Step 2: Get ObjectNode from JsonNodeFactory.
ObjectNode employee = factory.objectNode();

Step 3: Use set and put methods Object node to populate data.
employee.put("id", 1);
employee.put("firstName", "Hari Krishna");
employee.put("lastName", "Gurram");

ArrayNode hobbies = factory.arrayNode();
hobbies.add("Trekking").add("Blogging").add("Cooking");

employee.set("hobbies", hobbies);

Step 4: Use mapper.writeValueAsString() method to get JSON representation of ObjectNode.
mapper.writeValueAsString(employee)
Following is the complete working application.

import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class Main {
  public static void main(String args[]) throws IOException {
    JsonNodeFactory factory = new JsonNodeFactory(false);
    ObjectMapper mapper = new ObjectMapper();

    ObjectNode employee = factory.objectNode();

    employee.put("id", 1);
    employee.put("firstName", "Hari Krishna");
    employee.put("lastName", "Gurram");

    ArrayNode hobbies = factory.arrayNode();
    hobbies.add("Trekking").add("Blogging").add("Cooking");

    employee.set("hobbies", hobbies);

    System.out.println(mapper.writeValueAsString(employee));

  }
}


Output

{"id":1,"firstName":"Hari Krishna","lastName":"Gurram","hobbies":["Trekking","Blogging","Cooking"]}






Prevoius                                                 Next                                                 Home

No comments:

Post a Comment