Java JsonRawValue-class And Method Code Example

Here is an example of how to use the JsonRawValue class from the Apache Commons IO library to serialize a POJO to JSON and include a raw JSON value within it:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

public class Example {

    public static class MyPojo {

        private String name;

        @JsonSerialize(using = JsonRawValueSerializer.class)
        private String jsonData;

        // getters and setters

    public static void main(String[] args) throws Exception {
        MyPojo pojo = new MyPojo();
        pojo.setName("John Doe");

        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(pojo);

    public static class JsonRawValueSerializer extends JsonSerializer<String> {
        public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            gen.writeRawValue(value, JsonStringEncoder.getInstance());

This will output the following JSON:

    "name": "John Doe",
    "jsonData": {"key":"value"}

Note: This is using the Jackson JSON library to serialize the POJO to JSON. You need to have the jackson-databind jar in your classpath for this to work.