Jackson @JsonRawValue for map value

I have the following Java bean class that converts to JSON using Jackson.

  public class Thing {
    public String name;

    @JsonRawValue
    public Map content = new HashMap();
  }

contentis a map whose values ​​will be raw JSON from another source. For instance:

String jsonFromElsewhere = "{ \"foo\": \"bar\" }";

Thing t = new Thing();
t.name = "test";
t.content.put("1", jsonFromElsewhere);

Desired generated JSON:

{"name":"test","content":{"1":{ "foo": "bar" }}}

However, use @JsonRawValueresults in:

{"name":"test","content":{1={ "foo": "bar" }}}

I need a way to specify @JsonRawValueonly for the value of the map. Is this possible with Jackson?

+5
source share
2 answers

No. You can easily create a custom JsonSerializerone to do this, though.

Alternatively, maybe just use a disposable POJO:

public class RawHolder {
   @JsonProperty("1")
   public String raw;
}

public class Thing {
   public String name;
   public RawHolder content;
}
+2
source

As StaxMan points out, it's pretty easy to implement custom JsonSerializer.

public class Thing {
    public String name;

    @JsonSerialize(using=MySerializer.class)
    public Map<String, String> content = new HashMap<String, String>();
}

public class MySerializer extends JsonSerializer<Map<String, String>> {
    public void serialize(Map<String, String> value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        jgen.writeStartObject();
        for (Map.Entry<String, String> e: value.entrySet()) {
            jgen.writeFieldName(e.getKey());
            // Write value as raw data, since it already JSON text
            jgen.writeRawValue(e.getValue());
        }
        jgen.writeEndObject();
    }
}
+5
source

All Articles