簡體   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