在我的JSON数据中,我有很多字段,其中一些我想合并到一个对象中
我可以使用JsonDeserializer
实现该功能吗?
JSON示例:
{
field1 : "value1",
field2 : "value2",
field3 : "value3"
}
我需要的结果是:
class ClassA {
ClassB field1And2;
String field3;
}
class ClassB {
String field1;
String field2;
}
答案 0 :(得分:0)
我认为我们可以。见下文。
@JsonDeserialize(using=ChildDeserializer.class)
class Child{
private Name name;
private int age=13;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Name getName() {
return name;
}
public void setName(Name name) {
this.name = name;
}
}
class Name {
private String chFName;
private String chLName;
public Name(String f, String l) {
chFName=f;
chLName=l;
}
public String getChFName() {
return chFName;
}
public void setChFName(String chFName) {
this.chFName = chFName;
}
public String getChLName() {
return chLName;
}
public void setChLName(String chLName) {
this.chLName = chLName;
}
}
class ChildDeserializer extends JsonDeserializer<Child> {
@Override
public Child deserialize(JsonParser jsonParser, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
String fName= node.get("fName").textValue();
String lName= node.get("lName").textValue();
int age= node.get("age").intValue();
Child ch = new Child();
ch.setName(new Name(fName, lName));
ch.setAge(age);
return ch;
}
}
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.readValue("{\"fName\":\"first\",\"lName\":\"last\",\"age\":13}", Child.class);
}