杰克逊:是否有可能将父对象的属性包含在嵌套对象中? [英] Jackson: is it possible to include property of parent object into nested object?
问题描述
我正在使用Jackson来序列化/反序列化JSON对象。
I'm using Jackson to serialize/deserialize JSON objects.
我有研究
对象:
{
"studyId": 324,
"patientId": 12,
"patient": {
"name": "John",
"lastName": "Doe"
}
}
更新:不幸的是,JSON结构无法修改。这是问题的一部分。
UPDATE: Unfortunately the JSON structure cannot be modified. It's part of the problem.
我想将对象反序列化为以下类:
I would like to deserialize the object to the following classes:
public class Study {
Integer studyId;
Patient patient;
}
和
public class Patient {
Integer patientId;
String name;
String lastName;
}
是否可以包含 patientId $
Patient
对象中的c $ c>属性?
Is it possible to include the patientId
property in the Patient
object?
我可以反序列化患者
对象进入患者
类(具有相应的名称
和 lastName
属性),但无法包含 patientId
属性。
I am able to deserialize the patient
object into the Patient
class (with the corresponding name
and lastName
properties), but unable to include the patientId
property.
任何想法?
推荐答案
您可以为自己的用例使用自定义反序列化程序。这是它的样子:
You can use a custom deserializer for your use case. Here is what it will look like:
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
public class StudyDeserializer extends JsonDeserializer<Study>
{
@Override
public Study deserialize(JsonParser parser, DeserializationContext context)
throws IOException, JsonProcessingException
{
JsonNode studyNode = parser.readValueAsTree();
Study study = new Study();
study.setStudyId(studyNode.get("studyId").asInt());
Patient patient = new Patient();
JsonNode patientNode = studyNode.get("patient");
patient.setPatientId(studyNode.get("patientId").asInt());
patient.setName(patientNode.get("name").asText());
patient.setLastName(patientNode.get("lastName").asText());
study.setPatient(patient);
return study;
}
}
在<$中指定上述类作为反序列化器c $ c> Study class:
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
@JsonDeserialize(using = StudyDeserializer.class)
public class Study
{
Integer studyId;
Patient patient;
// Getters and setters
}
现在,您指定的JSON输入应按预期反序列化。
Now, the JSON input you have specified should get deserialized as expected.
这篇关于杰克逊:是否有可能将父对象的属性包含在嵌套对象中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!