java - 如何在 Spring Boot Java 中为动态 JSON 结构创建类
问题描述
我有以下 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;
}
}
}
解决方案
我遇到了与此类似的情况,我的 JSON 可能没有一致的键值对。我在类级别给出了以下杰克逊注释,以便我的模型中不可用的任何属性以及 JSON 中存在的属性都将被忽略。
@JsonIgnoreProperties(ignoreUnknown = true)
推荐阅读
- spring-boot - 第一个服务器命中的 Whitelabel 错误页面 - Spring Boot
- nginx - “/etc/nginx/sites-enabled/example.com”在/etc/nginx/nginx.conf:62中失败(2:没有这样的文件或目录)
- java - Hadoop 和重用的可变可写字段
- python - 如何通过检查 2 列中的值将 1 df 的列映射为另一个 df
- c++ - 我应该在复制赋值运算符中使用placement-new
- python - 有没有办法继续打印 Python 3 字典中的随机元素而不重复?
- c# - 格式化 api JSON 响应以将属性添加到数组
- python - 如何创建一个返回相关值(键)的字典?
- azure - 如何从 Azure 命令“powershell 中的 az group list”的“结果”数组中仅选择一个属性?
- python - json.decoder.JSONDecodeError:期望值:第 1 行第 1 列(字符 0) KeyError:[“数据字节 1:”]