杰克逊:是否有可能将父对象的属性包含在嵌套对象中?

mon*_*lbo 3 json jackson deserialization

我正在使用Jackson来序列化/反序列化JSON对象.

我有一个Study对象的以下JSON :

{
    "studyId": 324,
    "patientId": 12,
    "patient": {
        "name": "John",
        "lastName": "Doe"
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:不幸的是,JSON结构无法修改.这是问题的一部分.

我想将对象反序列化为以下类:

public class Study {
    Integer studyId;
    Patient patient;
}
Run Code Online (Sandbox Code Playgroud)

public class Patient {
    Integer patientId;
    String name;
    String lastName;
}
Run Code Online (Sandbox Code Playgroud)

是否可以patientIdPatient对象中包含属性?

我能够反序列化patient对象到Patient类(对应namelastName性质),但不能包含patientId属性.

有任何想法吗?

Jac*_*all 6

您可以为自己的用例使用自定义反序列化程序.这是它的样子:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

在类中指定上面的类作为反序列化器Study:

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

@JsonDeserialize(using = StudyDeserializer.class)
public class Study
{
    Integer studyId;
    Patient patient;

    // Getters and setters
}
Run Code Online (Sandbox Code Playgroud)

现在,您指定的JSON输入应按预期反序列化.