How to assemble JSON directly in Jackson

Introduction

Occasionally I will write Java code ... (No, it is the main language in my business), so I will post what I researched in the case I am currently in charge of.

Do you use Spring Framework? Recently, the server side is often built with Node.js, Ruby, etc., and the PaaS side has a mechanism that can easily provide Web API, so it is quite rare to implement it in Java. I'm wondering, but I'm still active, so I'm still coding Java in the current project.

This time it is a little unusual specification, and instead of mapping the JSON received by the Web API built in Spring Framework to POJO, we decided to process it as it is (dynamically) and bridge it to another Web API. Then, when I looked at the Javadoc, I wondered how I should have created JSON without using POJO in Jackson, and found that I should do the following.

Create an ObjectNode in Jackson

ʻObjectMapper provided a method called createObjectNode () `. You can use it to create an empty JSON object.

Use put (fieldName, value) to add a simple value to this object. Use set (fieldName, value) when adding an object or array.

Below is an example.

ObjectMapper mapper = new ObjectMapper();
ObjectNode root = mapper.createObjectNode();
root.put("stringValue", "test");
root.set("brankObject", mapper.createObjectNode());

Create an ArrayNode with Jackson

When dealing with arrays, ʻObjectMapper provided a method called createArrayNode () . You can use it to create an empty JSON array. Use ʻadd (value) to add elements to this array.

Below is an example.

ObjectMapper mapper = new ObjectMapper();
ArrayNode array = mapper.createArrayNode();
array.add("value");
array.add(mapper.createObjectNode());

Example of constructing JSON

It's a waste, but if you assemble JSON from POJO by yourself, it will be like this.

public class Test {
    public List<Item> items = Arrays.asList(
            new Item("Item 1", "$19.99", Arrays.asList(new Feature("New!"), new Feature("Awesome!"))),
            new Item("Item 2","$29.99", Arrays.asList(new Feature("Old."), new Feature("Ugly."))));

    public static class Item {
        Item(String name, String price, List<Feature> features) {
            this.name = name;
            this.price = price;
            this.features = features;
        }

        public String name, price;
        public List<Feature> features;
    }

    public static class Feature {
        Feature(String description) {
            this.description = description;
        }

        public String description;
    }
    
    public static void main(String[] args) throws IOException {
        Test test = new Test();

        ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
        ObjectNode root = mapper.createObjectNode();
        ArrayNode items = mapper.createArrayNode();
        for (Item itemsObj : test.items) {
            ObjectNode item = mapper.createObjectNode();
            item.put("name", itemsObj.name);
            item.put("price", itemsObj.price);
            ArrayNode features = mapper.createArrayNode();
            for (Feature featuresObj : itemsObj.features) {
                ObjectNode feature = mapper.createObjectNode();
                feature.put("description", featuresObj.description);
                features.add(feature);
            }
            item.set("features", features);
            items.add(item);
        }
        root.set("items", items);

        System.out.println(mapper.writeValueAsString(root));
        //After all, the output result will be the same as below
        // System.out.println(mapper.writeValueAsString(test));
    }
}

Output result

{
  "items" : [ {
    "name" : "Item 1",
    "price" : "$19.99",
    "features" : [ {
      "description" : "New!"
    }, {
      "description" : "Awesome!"
    } ]
  }, {
    "name" : "Item 2",
    "price" : "$29.99",
    "features" : [ {
      "description" : "Old."
    }, {
      "description" : "Ugly."
    } ]
  } ]
}

Summary

Performance etc. are not considered so much, but please refer to it when building JSON directly with Java + Jackson.

Recommended Posts

How to assemble JSON directly in Jackson
Understand how to use Swift's JSON Decoder in 3 minutes
How to use JSON data in WebSocket communication (Java, JavaScript)
How to use Lombok in Spring
How to run JUnit in Eclipse
How to iterate infinitely in Ruby
[Rails] How to write in Japanese
How to run Ant in Gradle
How to master programming in 3 months
How to learn JAVA in 7 days
How to get parameters in Spark
How to install Bootstrap in Ruby
How to introduce jQuery in Rails 6
How to use classes in Java?
How to name variables in Java
How to set Lombok in Eclipse
How to concatenate strings in java
How to install Swiper in Rails
How to POST JSON in Java-Method using OkHttp3 and method using HttpUrlConnection-
I want to get some properties as JSON strings in Jackson!
[swift5] How to specify color in hexadecimal
How to implement search functionality in Rails
How to implement Kalman filter in Java
How to change app name in rails
How to get date data in Ruby
How to use custom helpers in rails
How to reflect seeds.rb in production environment
How to use named volume in docker-compose.yml
How to filter JUnit Test in Gradle
How to insert a video in Rails
How to standardize header footer in Thymeleaf
How to add jar file in ScalaIDE
[Swift] How to fix Label in UIPickerView
How to use Docker in VSCode DevContainer
How to use MySQL in Rails tutorial
How to embed Janus Graph in Java
[rails] How to configure routing in resources
To write Response data directly in Spring
How to map tsrange type in Hibernate
How to get the date in java
How to implement ranking functionality in Rails
How to use environment variables in RubyOnRails
How to implement asynchronous processing in Outsystems
How to publish a library in jCenter
How to specify id attribute in JSF
Understand in 5 minutes !! How to use Docker
How to overwrite Firebase data in Swift
How to execute multiple commands in docker-compose.yml
[For beginners] How to debug in Eclipse
How to use ExpandableListView in Android Studio
How to display error messages in Japanese
Sample code to serialize and deserialize Java Enum enums and JSON in Jackson
Android development, how to check null in the value of JSON object
Summary of how to select elements in Selenium
How to get keycloak credentials in interceptor class
[JavaFX] How to write Eclipse permissions in build.gradle
(Memo) How to solve dummy output in Ubuntu 20.04
How to check the logs in the Docker container
How to color code console output in Eclipse
[Rails] How to use select boxes in Ransack
Code to escape a JSON string in Java