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

How to define JSON Schema for Map<String, Integer>?

我有一个 json :

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

这里的 itemTypes 和 itemCounts 是通用的,但它们内部的值(食品、NA、电气)不是,它们会不断变化,但格式为:Map

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

我试过了:

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

    }

您可以:

{
  "type": "object",
  "properties": {
    "itemType": {"$ref": "#/definitions/mapInt"},
    "itemCount": {"$ref": "#/definitions/mapInt"}
  },
  "definitions": {
    "mapInt": {
      "type": "object",
      "additionalProperties": {"type": "integer"}
    }
  }
}
{
    "type": "array",
    "maxItems": 125,
    "items": {
        "type": "array",
        "items": [
            { // key schema goes here },
            { // value schema goes here }
        ],
        "additionalItems": false
    }
}

这个问题描述的有点不好,我看看能不能改一下再回答一下。

问题:如何在 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"
    }
  }
}
"properties": {
  "myFieldName": {
    "existingJavaType" : "java.util.Map<String,String>",
    "type" : "object"
  }
}

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