Home > Software engineering >  How to put Java object to ObjectNode in Jackson?
How to put Java object to ObjectNode in Jackson?

Time:04-26

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?

CodePudding user response:

Can use set(String propertyName, JsonNode node) method.

CodePudding user response:

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());
  • Related