Search code examples
javascriptjavajsonjacksonnashorn

Mapping JSON objects in Java


What is the best way to map JSON objects in Java? I'm talking about something like Dozer or MapStruct for JavaBeans but for JSON. I found these two projects:

JSON Mapper 1

JSON Mapper 2

But they are in Javascript. So is it a good idea to embed them in my Java application running them with Nashorn? Or is it better to use straightforward Jackson library? But the second would imply reading the JSON, mapping it to a Java object and then converting the Java Object to another JSON - seems not very nice to me.


Solution

  • You can't map from JSON to JSON in Java because JSON is not a native data type. At some point, you have to parse the JSON into a representation that is understood by Java in order to work with it.

    You don't need to marshal it into Java objects, though. You can read the JSON tree (with Jackson, GSON, etc) which will be an object-oriented representation of the JSON string. From there, you can construct your desired JSON output.