Lolmewn
Lolmewn

Reputation: 1521

Does Jackson not pretty print values annotated by @JsonRawValue?

I store JSON in my database and want to include this JSON in an API response as-is, without de-serializing before serializing the data. The data itself resides in a wrapper object. When serializing this wrapper, it appears the JSON from my database isn't pretty-printed alongside the rest of the data, giving really weird-looking responses.

I have written some example code to outline my issue:

import com.fasterxml.jackson.annotation.JsonRawValue;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class JacksonTest {

    private static final String EXPECTED_OUTPUT = "{\n" +
            "  \"wrapper\" : {\n" +
            "    \"data\" : {\n" +
            "      \"raw\" : \"test\"\n" +
            "    }\n" +
            "  }\n" +
            "}";
    private static final String RAW_JSON = "{\n" +
            "  \"raw\" : \"test\"\n" +
            "}";

    static class Pojo {

        @JsonRawValue
        private final String data;

        public Pojo(String data) {
            this.data = data;
        }

        public String getData() {
            return data;
        }

    }

    static class Wrapper {
        private final Pojo wrapper;

        public Wrapper() {
            wrapper = new Pojo(RAW_JSON);
        }

        @SuppressWarnings("unused")
        public Pojo getWrapper() {
            return wrapper;
        }
    }

    @Test
    void shouldEqual() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
        String output = mapper.writeValueAsString(new Wrapper());
        assertThat(output).isEqualTo(EXPECTED_OUTPUT);
    }

}

This test fails with the following output:

{
  "wrapper" : {
    "data" : {
  "raw" : "test"
}
  }
}

While I expect jackson to give me the following output:

{
  "wrapper" : {
    "data" : {
      "raw" : "test"
    }
  }
}

Is there any way to "fix" the indenting of the raw data that's annotated with @JsonRawValue?

Upvotes: 1

Views: 726

Answers (1)

BendaThierry.com
BendaThierry.com

Reputation: 2109

Maybe with the following code your test will pass :

Object json = mapper.readValue(input, Object.class);
String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);

You can check that stackoverflow question and its own answers from which the code I have written upper was coming from, from the accepted answer : Convert JSON String to Pretty Print JSON output using Jackson

Upvotes: 1

Related Questions