如何为Map定义JSON Schema<String, Integer>?

问题描述 投票:0回答:4

我有一个 json :

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

这里的 itemTypes 和 itemCounts 将是通用的,但它们内部的值(食物、NA、电气)不是通用的,它们会不断变化,但格式如下:地图

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

我试过了:

"itemCounts": {
    "type": "object""additionalProperties": {
        "string",
        "integer"
    }
}
json schema geojson jsonschema json-schema-validator
4个回答
38
投票

您可以:

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

6
投票

这个问题描述得不太好,让我看看是否可以改写并回答它。

问题:如何在 json 模式中表示地图,如下所示

Map<String, Something>

答案:

看起来可以用

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

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

例如,假设您想要一个

Map<string, string>

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

或者更复杂的东西,比如

Map<string, SomeStruct>

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

1
投票

使用“additionalProperties”有两个问题

  1. 它创建表示 Object 或 Int Map 的附加类,其内部具有 extraProperty 作为要用作 Map 的成员
  2. 因为它的additionalProperties,它总是有@JsonIgnore,所以它在序列化时不会出现。

所以在我看来,正确的方法是使用直接 Java 类型。

"properties": {
  "myFieldName": {
    "existingJavaType" : "java.util.Map<String,String>",
    "type" : "object"
  }
}

参考:https://www.jsonschema2pojo.org/


-4
投票
{
    "type": "array",
    "maxItems": 125,
    "items": {
        "type": "array",
        "items": [
            { // key schema goes here },
            { // value schema goes here }
        ],
        "additionalItems": false
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.