如何使用Jackson反序列化动态字段? [英] How to deserialize dynamic field using Jackson?

查看:656
本文介绍了如何使用Jackson反序列化动态字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下Json:

{
    "id": "id1",
    "version": "id1",
    "license": { "type": "MIT" }
}

其中也可以采用以下形式:

Which can also be in the form of:

{
    "id": "id1",
    "version": "id1",
    "license": "MIT"
}

有时它可以是:

{
    "id": "id1",
    "version": "id1",
    "licenses": [
    { "type": "MIT", "url: "path/to/mit" },
    { "type": "Apache2", "url: "path/to/apache" }]
}

以上所有内容基本相同,我正在寻找一种方法将它们与单个字段组合并使用Jackson对其进行反序列化。任何想法?

All of the above are essentially the same, I'm looking for a way to combine them with a single field and deserialize it using Jackson. Any Ideas?

推荐答案

首先,请看这个问题:杰克逊对具有不同对象的类型进行反序列化。您可以将JSON反序列化为低于POJO类:

At the beginning, please, see this this question: Jackson deserialization of type with different objects. You can deserialize your JSON to below POJO class:

class Entity {

    private String id;
    private String version;
    private JsonNode license;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public JsonNode getLicense() {
        return license;
    }

    public void setLicense(JsonNode license) {
        this.license = license;
    }

    public void setLicenses(JsonNode license) {
        this.license = license;
    }

    public String retrieveLicense() {
        if (license.isArray()) {
            return license.elements().next().path("type").asText();
        } else if (license.isObject()) {
            return license.path("type").asText();
        } else {
            return license.asText();
        }
    }

    @Override
    public String toString() {
        return "Entity [id=" + id + ", version=" + version + ", license=" + license + "]";
    }
}

使用 retrieveLicense 方法,如果要从POJO类中检索许可证名称。当然,您可以改进此方法的实现。我的示例仅显示了如何实现它的方式。如果要将POJO类与反序列化逻辑分离,可以编写自定义反序列化器。

Use retrieveLicense method if you want to retrieve licence name from the POJO class. Of course, you can improve implementation of this method. My example shows only the way how you can implement it. If you want to decouple POJO class from deserialization logic you can write custom deserializer.

这篇关于如何使用Jackson反序列化动态字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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