이의 당신의 JSON
이 같다고 가정하자 :
{
"input1" : "Input value",
"input2" : 3
}
그리고 당신의 POJO
클래스는 다음과 같습니다
class Entity {
private String input1;
private int input2;
private String calculated1;
private long calculated2;
...
}
을이 경우당신은 당신의 Entity
클래스에 대한 사용자 지정 디시리얼라이저를 작성할 수 있습니다 위의 클래스에서 당신은 Entity
이 recalculate
방법을 가지고 있음을 알 수
class EntityJsonDeserializer extends JsonDeserializer<Entity> {
@Override
public Entity deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException,
JsonProcessingException {
InnerEntity innerEntity = jp.readValueAs(InnerEntity.class);
Entity entity = new Entity();
entity.setInput1(innerEntity.input1);
entity.setInput2(innerEntity.input2);
entity.recalculate();
return entity;
}
public static class InnerEntity {
public String input1;
public int input2;
}
}
.
public void recalculate() {
calculated1 = input1 + input2;
calculated2 = input1.length() + input2;
}
이 논리를 deserializer 클래스로 이동할 수도 있습니다.
지금, 당신은 당신이 당신의 사용자 정의 디시리얼라이저를 사용하려면 Jackson
을 통보해야합니다 :
@JsonDeserialize(using = EntityJsonDeserializer.class)
class Entity {
...
}
아래의 예는 이러한 클래스를 사용하는 방법을 보여줍니다
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.readValue(json, Entity.class));
이 프로그램은 인쇄 :
를
Entity [input1=Input value, input2=3, calculated1=Input value3, calculated2=14]
"InnerEntity"는 어디서 오는가? –
이것은 "JSON 입력"을 역 직렬화 할 수있는 "EntityJsonDeserializer"의 내부 클래스입니다. –