杰克逊:是否有可能将父对象的属性包含在嵌套对象中? [英] Jackson: is it possible to include property of parent object into nested object?

查看:90
本文介绍了杰克逊:是否有可能将父对象的属性包含在嵌套对象中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆