Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting only the first level of object tree using Jackson ObjectMapper

Tags:

java

json

jackson

Is it possible to make ObjectMapper convert only the actual object without converting the rest of the object tree recursively ?

So that :

Map<String,Object> props = new ObjectMapper().convertValue(obj, Map.class);

results in a map of [field, value] where values are the actual references to instances of the fields of obj instead of Maps ?

like image 873
lisak Avatar asked May 21 '13 16:05

lisak


People also ask

How do I map nested values with Jackson?

Mapping With Annotations To map the nested brandName property, we first need to unpack the nested brand object to a Map and extract the name property. To map ownerName, we unpack the nested owner object to a Map and extract its name property.

How does ObjectMapper readValue work?

The simple readValue API of the ObjectMapper is a good entry point. We can use it to parse or deserialize JSON content into a Java object. Also, on the writing side, we can use the writeValue API to serialize any Java object as JSON output.

Should I declare Jackson's ObjectMapper as a static field?

Yes, that is safe and recommended.

What is ObjectMapper class in Jackson?

ObjectMapper is the main actor class of Jackson library. ObjectMapper class ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model (JsonNode), as well as related functionality for performing conversions.


1 Answers

There is no such feature right now with Jackson. You can probably achieve this with a custom Serializer/Deserializer pair that could share some data and "protocol". But, why bother doing this when the easier (and a LOT faster) way would be to have a generic way to go from POJO to Map, probably using reflection.

like image 162
Pascal Gélinas Avatar answered Oct 19 '22 16:10

Pascal Gélinas