【问题标题】:How to define JSON Schema for Map<String, Integer>?如何为 Map<String, Integer> 定义 JSON Schema?
【发布时间】:2017-04-06 15:05:42
【问题描述】:

我有一个 json :

{
"itemTypes": {"food":22,"electrical":2},
"itemCounts":{"NA":211}
}

这里的 itemTypes 和 itemCounts 很常见,但它们内部的值(食物、NA、电气)会不断变化,但格式为:Map

如何为这种通用结构定义 Json Schema?

我试过了:

"itemCounts":{
      "type": "object"
    "additionalProperties": {"string", "integer"}

    }

【问题讨论】:

  • 通过定义json shcema,你是问如何写一个代表json的类吗?
  • @J.West 无 JSON 格式的 Schema
  • 这是你要引用的example吗?

标签: json schema geojson jsonschema json-schema-validator


【解决方案1】:

你可以:

{
  "type": "object",
  "properties": {
    "itemType": {"$ref": "#/definitions/mapInt"},
    "itemCount": {"$ref": "#/definitions/mapInt"}
  },
  "definitions": {
    "mapInt": {
      "type": "object",
      "additionalProperties": {"type": "integer"}
    }
  }
}

【讨论】:

  • 我们如何指定这两者中的哪一个应该被视为“关键”?
  • 键在 JSON 中将始终为 strings。在此示例中,itemTypeitemCount 都是“字符串”到“整数”的映射。另请注意,您不必使用 definitions 事物来制作字符串到 int 的映射——这只是本示例中用于删除重复定义的快捷方式。
  • 我正在寻找如何表示Map&lt;number, number&gt;。我控制服务器和客户端以及序列化程序,但不知道如何将键定义为数字,有什么帮助吗?
  • @ttugates 您将无法在 JSON 模式中执行此操作,因为它不符合 JSON 规范
【解决方案2】:

这个问题描述得很糟糕,让我看看我是否可以改写它并回答它。

问题:如何像 Map&lt;String, Something&gt; 那样在 json 模式中表示地图

答案:

看来你可以用Additional Properties来表达https://json-schema.org/understanding-json-schema/reference/object.html#additional-properties

{
  "type": "object",
  "additionalProperties": { "type": "something" }
}

例如,假设您想要Map&lt;string, string&gt;

{
  "type": "object",
  "additionalProperties": { "type": "string" }
}

或者更复杂的东西,比如Map&lt;string, SomeStruct&gt;

{
  "type": "object",
  "additionalProperties": { 
    "type": "object",
    "properties": {
      "name": "stack overflow"
    }
  }
}

【讨论】:

    【解决方案3】:
    {
        "type": "array",
        "maxItems": 125,
        "items": {
            "type": "array",
            "items": [
                { // key schema goes here },
                { // value schema goes here }
            ],
            "additionalItems": false
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多