Close

Jackson JSON - Using @JsonRawValue to serialize property as it is

[Last Updated: Aug 11, 2020]

@JsonRawValue annotation can be used to serialize property as it is. The value is not escaped or quoted. This can be useful in the scenarios like when values already serialized in JSON or values have been already quoted.

Example

POJO

public class Report {
  private long id;
  private String name;
  @JsonRawValue
  private String content;
    .............
}

Serializing

public class ExampleMain {
  public static void main(String[] args) throws IOException {
      Report r = new Report();
      r.setId(1);
      r.setName("Test report");
      r.setContent("\"data\"");

      System.out.println("-- before serialization --");
      System.out.println(r);

      ObjectMapper om = new ObjectMapper();
      String jsonString = om.writeValueAsString(r);
      System.out.println("-- after serialization --");
      System.out.println(jsonString);
  }
}
-- before serialization --
Report{id=1, name='Test report', content='"data"'}
-- after serialization --
{"id":1,"name":"Test report","content":"data"}

Following example shows the 'content' field is already assign a JSON string:

public class ExampleMain2 {
  public static void main(String[] args) throws IOException {
      Report r = new Report();
      r.setId(1);
      r.setName("Test report");
      r.setContent("{\"author\":\"Peter\", \"content\":\"Test content\"}");

      System.out.println("-- before serialization --");
      System.out.println(r);

      ObjectMapper om = new ObjectMapper();
      String jsonString = om.writeValueAsString(r);
      System.out.println("-- after serialization --");
      System.out.println(jsonString);
  }
}
-- before serialization --
Report{id=1, name='Test report', content='{"author":"Peter", "content":"Test content"}'}
-- after serialization --
{"id":1,"name":"Test report","content":{"author":"Peter", "content":"Test content"}}

Without @JsonRawValue

If we remove @JsonRawValue from our Report#content field then output of the last example will be:

-- before serialization --
Report{id=1, name='Test report', content='{"author":"Peter", "content":"Test content"}'}
-- after serialization --
{"id":1,"name":"Test report","content":"{\"author\":\"Peter\", \"content\":\"Test content\"}"}

Example Project

Dependencies and Technologies Used:

  • jackson-databind 2.9.6: General data-binding functionality for Jackson: works on core streaming API.
  • JDK 10
  • Maven 3.5.4

@JsonRawValue Example Select All Download
  • jackson-json-raw-value-annotation-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Report.java

    See Also