[英]Jackson @JsonRawValue for Map's value
I have the following Java bean class with gets converted to JSON using Jackson. 我有以下Java bean类,使用Jackson转换为JSON。
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. content
是一个地图,其值将是来自其他来源的原始JSON。 For example: 例如:
String jsonFromElsewhere = "{ \"foo\": \"bar\" }";
Thing t = new Thing();
t.name = "test";
t.content.put("1", jsonFromElsewhere);
The desired generated JSON is: 所需的生成JSON是:
{"name":"test","content":{"1":{ "foo": "bar" }}}
However using @JsonRawValue
results in: 但是使用
@JsonRawValue
导致:
{"name":"test","content":{1={ "foo": "bar" }}}
What I need is a way to specify @JsonRawValue
for only for the Map's value. 我需要的是一种仅为Map的值指定
@JsonRawValue
的方法。 Is this possible with Jackson? 这可能与杰克逊有关吗?
As StaxMan points out, it's pretty easy to implement a custom JsonSerializer
. 正如StaxMan指出的那样,实现自定义
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();
}
}
No. You could easily create custom JsonSerializer
to do that though. 不。你可以轻松创建自定义
JsonSerializer
来做到这一点。
Also, maybe rather just use one-off POJO: 另外,也许只使用一次性POJO:
public class RawHolder {
@JsonProperty("1")
public String raw;
}
public class Thing {
public String name;
public RawHolder content;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.