Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson @JsonRawValue for Map's value

Tags:

java

json

jackson

I have the following Java bean class with gets converted to JSON using Jackson.

  public class Thing {
    public String name;

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

content is a map who's values will be raw JSON from another source. For example:

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

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

The desired generated JSON is:

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

However using @JsonRawValue results in:

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

What I need is a way to specify @JsonRawValue for only for the Map's value. Is this possible with Jackson?

like image 559
Steve Kuo Avatar asked Aug 24 '12 16:08

Steve Kuo


1 Answers

As StaxMan points out, it's pretty easy to implement a 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's already JSON text
            jgen.writeRawValue(e.getValue());
        }
        jgen.writeEndObject();
    }
}
like image 170
Steve Kuo Avatar answered Sep 28 '22 04:09

Steve Kuo