jackson-databind
jackson-databind copied to clipboard
`@JsonUnwrapped` does not work with JsonNode, should
JsonUnwrapped does not work with JsonNode. Using jackson-databind:jar:2.13.2.1
.
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public abstract class Widget {
private static ObjectMapper mapper = new ObjectMapper();
@JsonProperty
String widgetType;
public static void main(String[] args) throws JsonProcessingException {
String response = """
{
"foo": "bar",
"x": "y"
}
""";
JsonNode jsonNode = mapper.readTree(response);
DailyWidget dailyWidget = new DailyWidget();
dailyWidget.content = jsonNode;
dailyWidget.widgetType = "DAILY_WIDGET";
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(dailyWidget));
}
}
class DailyWidget extends Widget {
@JsonUnwrapped
JsonNode content;
}
Outputs:
{
"widgetType" : "DAILY_WIDGET",
"content" : {
"foo" : "bar",
"x" : "y"
}
}
I expect this output:
{
"widgetType" : "DAILY_WIDGET",
"foo" : "bar",
"x" : "y"
}
Correct: currently JsonNode
does not consider @JsonUnwrapped
. It'd make sense for that to be available I suppose.
PRs welcome.
Note: serialization would likely be easy enough to support; deserialization more challenging.
Thinking about this now, I think that what would actually also work here -- but not yet implemented either -- would be to allow use of @JsonAnyGetter
on ObjectNode
(or maybe JsonNode
generally) valued fields/getters.
I filed #3604 for this.