【问题标题】:How to create class for dynamic JSON structure in Spring Boot Java如何在 Spring Boot Java 中为动态 JSON 结构创建类
【发布时间】:2023-04-06 07:12:02
【问题描述】:

我有以下 JSON 结构作为输入,可以嵌套和不嵌套。我想获取 JSON 作为 Spring Boot 应用程序中的输入和进程。如何在 JSON 中创建一个动态键值的类。它可以是 JSON 输入中的任何键值对。下面是一个示例。

没有嵌套:

{
    "mappings": {
        "properties": {
            "firstname": {
                "type": "string"
            },
            "lastname": {
                "type": "string"
            },
            "salary": {
                "type": "integer"
            },
            "date_of_birth": {
                "type": "date"
            }
        }
    }
}

嵌套:

{
    "mappings": {
        "properties": {
            "firstname": {
                "type": "string"
            },
            "lastname": {
                "type": "string"
            },
            "annual_salary": {
                "type": "integer"
            },
            "date_of_birth": {
                "type": "date"
            },
            "comments": {
                "type": "nested",
                "properties": {
                    "name": {
                        "type": "string"
                    },
                    "comment": {
                        "type": "string"
                    },
                    "age": {
                        "type": "short"
                    },
                    "stars": {
                        "type": "short"
                    },
                    "date": {
                        "type": "date"
                    }
                }
            }
        }
    }
}

我不知道如何创建一个类来支持嵌套和不嵌套在单个类中。我尝试了以下方法。没用。

public class Schema {
    Mapping mappings;

    public Mapping getMappings() {
        return mappings;
    }

    public void setMappings(Mapping mappings) {
        this.mappings = mappings;
    }

    public static class Mapping {
        Property properties;

        public Property getProperties() {
            return properties;
        }

        public void setProperties(Property properties) {
            this.properties = properties;
        }
    }

    public static class Property {
        Map<String, Map<String, Object>> field = new HashMap<>();

        public Map<String, Map<String, Object>> getField() {
            return field;
        }

        public void setField(Map<String, Map<String, Object>> field) {
            this.field = field;
        }
    }
}

【问题讨论】:

    标签: java spring-boot jackson javabeans jsontemplate


    【解决方案1】:

    我遇到过类似的情况,我的 JSON 可能没有一致的键值对。 我在类级别给出了以下杰克逊注释,以便我的模型中不可用的任何属性以及 JSON 中存在的属性都将被忽略。

    @JsonIgnoreProperties(ignoreUnknown = true)
    

    【讨论】:

      猜你喜欢
      • 2010-12-16
      • 1970-01-01
      • 2017-01-10
      • 1970-01-01
      • 2017-04-18
      • 1970-01-01
      • 2019-12-16
      • 2020-10-11
      • 1970-01-01
      相关资源
      最近更新 更多