Reputation: 63094
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?
Upvotes: 8
Views: 7517
Reputation: 63094
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();
}
}
Upvotes: 7
Reputation: 116512
No. You could easily create custom JsonSerializer
to do that though.
Also, maybe rather just use one-off POJO:
public class RawHolder {
@JsonProperty("1")
public String raw;
}
public class Thing {
public String name;
public RawHolder content;
}
Upvotes: 2