jackson-databind icon indicating copy to clipboard operation
jackson-databind copied to clipboard

`@JsonUnwrapped` does not work with JsonNode, should

Open G0dC0der opened this issue 1 year ago • 2 comments

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"
}

G0dC0der avatar Sep 07 '22 16:09 G0dC0der

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.

cowtowncoder avatar Sep 08 '22 00:09 cowtowncoder

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.

cowtowncoder avatar Sep 23 '22 05:09 cowtowncoder