사용자 지정 맵을 JSON으로 직렬화하고 싶습니다.
지도 인터페이스를 구현하는 클래스는 다음과 같습니다.
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);
Jackson은 맵을 직렬화하고 변수를 무시합니다. 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"인터페이스를 추출하고 @JsonSerialize (as = ...) 주석을 통해 직렬화 할 때 Jackson에게 대신 사용하도록 지시 할 수 있습니다.
어떻게 작동하는지 설명하기 위해 예제를 약간 수정했습니다. 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);
}
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다