我想将自定义Map序列化为JSON。
实现map接口的类如下:
public class MapImpl extends ForwardingMap<String, String> {
//ForwardingMap comes from Guava
private String specialInfo;
private HashMap<String, String> delegate;
@Override
protected Map<String, String> delegate() {
return this.delegate;
}
// some getters....
}
如果我现在打电话
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("/somePath/myJson.json"), objectOfMapImpl);
杰克逊将序列化地图并忽略变量specialInfo
我尝试了JsonSerializer
的自定义实现,但我最终得到了这个代码段:
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule("someModule");
module.addSerializer(CheapestResponseDates.class, new JsonSerializer<MapImpl>() {
@Override
public void serialize(final MapImpl value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException {
CheapestResponseDurations.class);
// how to serialize the map here? maybe be in a data node...
jgen.writeStartObject();
jgen.writeObjectField("info", value.getInfo());
jgen.writeEndObject();
}
});
mapper.registerModule(module);
我正在使用JDK 1.7和Jackson 2.3.1
答案 0 :(得分:5)
您可以使用@ {JSONAnySetter / @JsonAnyGetter注释,如this blog post中所述。因为,正如您所提到的,您的自定义地图类必须实现Map接口,您可以提取一个单独的“bean”接口,并告诉Jackson在通过@JsonSerialize(as = ...)注释进行序列化时使用它。
我稍微修改了你的例子来说明它是如何工作的。请注意,如果要将json字符串反序列化回地图对象,则可能需要执行其他一些操作。
public class MapSerialize {
public static interface MyInterface {
String getSpecialInfo();
@JsonAnyGetter
Map<String, String> delegate();
}
@JsonSerialize(as = MyInterface.class)
public static class MyImpl extends ForwardingMap<String, String> implements MyInterface {
private String specialInfo;
private HashMap<String, String> delegate = new HashMap<String, String>();
public Map<String, String> delegate() {
return this.delegate;
}
@Override
public String getSpecialInfo() {
return specialInfo;
}
public void setSpecialInfo(String specialInfo) {
this.specialInfo = specialInfo;
}
@Override
public String put(String key, String value) {
return delegate.put(key, value);
}
}
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
MyImpl objectOfMapImpl = new MyImpl();
objectOfMapImpl.setSpecialInfo("specialInfo");
objectOfMapImpl.put("XXX", "YYY");
String json = mapper.writeValueAsString(objectOfMapImpl);
System.out.println(json);
}
}