jesantana jesantana - 5 months ago 20
Java Question

Map from JSON to java object with different structure

I have a JSON string representing an object, and I want to put its information into a Java object

B
with a different structure. Currently the solution I am taking is creating a Java Object
A
with a structure identical to the JSON object, made the conversion from JSON to
A
using Jackson and later, made the mapping from
A
to
B
using Dozer with XML mappings. Is there anyway to avoid having the
A
objects?

Making it short, currently I have this:

JSON--Jackson-->A--Dozer(XML mappings)-->B


and I would like to achieve this

JSON--???-->B

Answer

You may know this already, but Jackson can use loosely structure types like Map, or JsonNode as target, so you can do, say:

JsonNode root = mapper.readTree(jsonSource); Map<String,Object> asMap = mapper.readValue(jsonSource, Map.class);

and then construct your B. Jackson has only limited amount of structural conversions (simple unwrapping), by design, although there is extensive set of scalar conversions (non-structural conversions), so if you do need structural changes it may make sense to use a library that is focused on structural changes.

Comments