[英]Serialize a custom map with Jackson
我想將自定義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
您可以利用@ JsonAnySetter / @JsonAnyGetter注釋,如本博文中所述。 因為,正如您所提到的,您的自定義地圖類必須實現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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.