I use the following to convert a JSON into an Object:
JSON:
{
"color": "blue"
}
Code:
somethingDto = objectMapper.readValue(myJson, SomethingDTO.class);
However, let’s say that the JSON comes at the following format:
{
"something": {
"color": "blue"
}
}
What code can achieve the same result?
Edit: There may be more properties alongside "something"
2
Answers
You should create a root class for it for example
Then map your JSON to it
Or you can use JsonNode
Also, you can handle both of them in this way
Threre is an annotation called
@JsonRootName
which is similar to@XmlRootElement
. That annotation indicates the name of the "root" wrapping.After that, the fearure must be enabled:
Now, it will wrap / unwrap objects to desired root element(s).