Adam Bronfin
Adam Bronfin

Reputation: 1279

Java jackson how to unwrap a raw value during serialization?

Using the Jackson json library in Java, is it possible to do the following:

public class MyObject {
     @JsonRawValue
     @JsonUnwrapped
     private String rawJson;

}

public class DTO {

     public MyObject json;

}

Example of rawJson:

{
    "key": "value"
}

When DTO is serialized and rendered as json, I want the JSON to simply look like:

{
   "dto": {
         "key":"value"

    }
}

Instead it's always:

{
   "dto":{
      "rawJson":{
         "key":"value"
      }
   }
}

Basically it seems that when one of your properties is a JSON value stored in a string with @JsonRawValue, @JsonUnwrapped doesn't work.

Ideally I'm looking for a serialization solution at the level of the MyObject class rather than DTO, or else I'd have to apply the solution to not only DTO but every other DTO where MyObject is referenced.

Update:

The below answer solved this problem in one location, but still is an issue in the following scenario;

public class DTO2 {
     @JsonUnwrapped
     public MyObjectAbstract json2;
}

Where MyObject is an extension of MyObjectAbstract, and when DTO2 MyObjectAbstract is an instance of MyObject I'd like DTO2 to simply be serialized as:

{
    "key": "value"
}

The issue is that whenever DTO2.MyObjectAbstract is an instance of MyObject it's serialized like:

{
    "json": {
        "key": "value"
    }
}

Upvotes: 4

Views: 2592

Answers (1)

Alexey Gavrilov
Alexey Gavrilov

Reputation: 10853

You can use JsonRawValue and JsonValueannotations on a getter method instead. Here is an example:

public class JacksonUnwrapped {

    static class MyObject {
        private String rawJson;

        MyObject(final String rawJson) {
            this.rawJson = rawJson;
        }

        @JsonRawValue
        @JsonValue
        String getRawJson() {
            return rawJson;
        }
    }

    static class DTO {
        public MyObject json;

        DTO(final MyObject json) {
            this.json = json;
        }
    }

    public static void main(String[] args) throws JsonProcessingException {
        final ObjectMapper objectMapper = new ObjectMapper();
        final DTO dto = new DTO(new MyObject(
                "{\"key\": \"value\"}"));
        System.out.println(objectMapper
                .writerWithDefaultPrettyPrinter()
                .writeValueAsString(dto));
    }

}

Output:

{
  "json" : {"key": "value"}
}

Upvotes: 2

Related Questions