Java 如何为名称/值结构创建 JSON 模式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22229250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create JSON Schema for Name/Value structure?
提问by Damian Leszczyński - Vash
My problem is that i am serializing the content of map to JSON.
我的问题是我正在将地图的内容序列化为 JSON。
In the output (JSON), i have object that follow key/name syntax rule.
在输出(JSON)中,我有遵循键/名称语法规则的对象。
The key is created from map key, and the name from the value.
键是从映射键创建的,名称来自值。
Model Example:
模型示例:
class Storage {
Map<String,String> values = new HashMap<>();
{
map.put("key1","key1");
map.put("key2","key2");
map.put("key3","key3");
}
}
JSON Example object:
JSON 示例对象:
{
key1=value1,
key2=value2,
key3=value3
}
JSON Schema:
JSON 架构:
{
"name": "storage",
"description": "Store of key values",
"properties": {
// How can we describe the properties if we do not know the name ?
}
}
The issue is that i do not know what the values will be but i know that they will be some.
问题是我不知道这些值会是什么,但我知道它们会是一些。
Can you help me to provide me the full definition of schema?
你能帮我提供模式的完整定义吗?
Disclaimer:
免责声明:
I know that this can be also serialized as
我知道这也可以序列化为
{
values: [
{key="key1", value="value1"},
{key="key2", value="value2"},
{key="key3", value="value3"}
]
}
but is do not want to have array in the JSON.
但不想在 JSON 中有数组。
采纳答案by McDowell
Assuming your validator supports it you can use patternProperties.
假设您的验证器支持它,您可以使用patternProperties。
For the schema...
对于架构...
{
"title": "Map<String,String>",
"type": "object",
"patternProperties": {
".{1,}": { "type": "string" }
}
}
...and the document...
……还有文件……
{
"foo":"bar",
"baz":1
}
...the value of property foois valid because it is a string but bazfails validation because it is a number.
...属性foo的值是有效的,因为它是一个字符串,但baz验证失败,因为它是一个数字。
回答by Abdeali Chandanwala
I used the Solution suggested by @augurar "additionalProperties": { "type": "string" }
我使用了@augurar "additionalProperties": { "type": "string" } 建议的解决方案
for AWS API Gateway Model .... and the SDK was able to generate the Map variable as required in Java / Android SDK
用于 AWS API 网关模型 .... 并且 SDK 能够根据 Java / Android SDK 的要求生成 Map 变量
@Arne Burmeister - in my case - Solution 1 didnt worked as needed - although it didnt gave any error in the Model (Schema Created)
@Arne Burmeister - 在我的情况下 - 解决方案 1 没有按需要工作 - 尽管它在模型中没有给出任何错误(架构创建)