繁体   English   中英

如何在 Spring 启动 ZD52387880E1EA22817A8972D375921 中为动态 JSON 结构创建 class

[英]How to create class for dynamic JSON structure in Spring Boot Java

我有以下 JSON 结构作为可以嵌套和不嵌套的输入。 我想获取 JSON 作为 Spring 引导应用程序中的输入和处理。 如何在 JSON 中创建一个 class 动态键值。 它可以是 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"
                    }
                }
            }
        }
    }
}

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

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;
        }
    }
}

我遇到了与此类似的情况,我的 JSON 可能没有一致的键值对。 I gave the following jackson annotation at class level so that whichever property not available in my model and which are present in the JSON will be ignored.

@JsonIgnoreProperties(ignoreUnknown = true)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM