オブジェクト固有のカスタムデシリアライザを作成する必要があります。
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import java.io.IOException;
class JacksonDeserializerTest {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule("CustomPersonDeserializer", new Version(1, 0, 0, null, null, null));
module.addDeserializer(Person.class, new CustomPersonDeserializer());
mapper.registerModule(module);
String jsonString = "{ \"id\": 1, \"name\": \"User 1 \"}";
Person user = mapper.readValue(jsonString, Person.class);
System.out.println("User: " + user.toString());
jsonString = "{ \"id\": 1}";
user = mapper.readValue(jsonString, Person.class);
}
static class CustomPersonDeserializer extends StdDeserializer<Person> {
private static final long serialVersionUID = -4100181951833318756L;
public CustomPersonDeserializer() {
this(null);
}
public CustomPersonDeserializer(Class<?> vc) {
super(vc);
}
@Override
public Person deserialize(JsonParser parser, DeserializationContext deserializer) throws IOException, JsonProcessingException {
Person person = new Person();
ObjectCodec codec = parser.getCodec();
JsonNode node = codec.readTree(parser);
JsonNode idNode = node.get("id");
int id = idNode.asInt();
person.setId(id);
JsonNode nameNode = node.get("name");
if(nameNode == null){
throw new IOException("name must be provided");
}
String name = nameNode.asText();
if (name.trim().length() < 1){
throw new IOException("name can not be empty");
}
person.setName(name);
return person;
}
}
static class Person {
private int id;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", id=" + id +
'}';
}
}
}
クリエイターメソッドのパラメーターにバインドされたプロパティに対してのみ機能しませんか?私はコンストラクタまたは静的ファクトリメソッドを意味します。 –
@CassioMazzochiMolin私はそう思いますが、それは本当に問題ではありません。 –