Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
    }
}
like image 597
Adam Bronfin Avatar asked Oct 16 '25 23:10

Adam Bronfin


1 Answers

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"}
}
like image 107
Alexey Gavrilov Avatar answered Oct 19 '25 12:10

Alexey Gavrilov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!