javajsonjackson

How to put Java object to ObjectNode in Jackson?


I am composing ObjectNode programmtically and I am filling it's fields with put(String propertyName...) methods. Now I want to add a subobject, which I already have in the form of Java object. How to do this?

I don't have put(String propertyName, Object value) method, so what to do?

I am able to create

JsonNode node = mapper.valueToTree(myObject);

but again I don't have put(String propertyName, JsonNode node) method.

How to accomplish?


Solution

  • Try using set(String, JsonNode) instead of put. Example below:

    Car car = new Car();
    car.setName("My car");
    car.setYear("2022");
    
    ObjectMapper mapper = new ObjectMapper();
    
    ObjectNode baseNode = mapper.createObjectNode();
    ObjectNode carNode = mapper.valueToTree(car);
    
    baseNode.put("hello", "world");
    baseNode.set("car", carNode);
    
    System.out.println(baseNode.toPrettyString());