4

我需要从 JSON 模式文件生成 Java 类并遇到 jsonschema2pojo。ref但是,我在使用关键字时遇到了一个“问题” 。

例如,如果我使用来自http://spacetelescope.github.io/understanding-json-schema/structuring.html#extending的以下模式:

{
  "$schema": "http://json-schema.org/draft-04/schema#",

  "definitions": {
    "address": {
      "type": "object",
      "properties": {
        "street_address": { "type": "string" },
        "city":           { "type": "string" },
        "state":          { "type": "string" }
      },
      "required": ["street_address", "city", "state"]
    }
  },

  "type": "object",

  "properties": {
    "billing_address": { "$ref": "#/definitions/address" },
    "shipping_address": { "$ref": "#/definitions/address" }
  }
}

正如预期的那样,它生成了一个类,无论你想怎么称呼它,都包含一个属性billingAddress和一个属性shippingAddress

但是,它也生成了两个单独的类BillingAddressShippingAddress即使两个属性都引用address. 因此,我宁愿同时拥有 type 的两个属性Address

这可以用 jsonschema2pojo 实现吗?

4

1 回答 1

4

更新

在从这里对 javaType 有了更好的理解之后。我只需在您的地址定义中添加一个 javaType 即可获得预期的结果。

{
  "$schema": "http://json-schema.org/draft-04/schema#",

  "definitions": {
      "address": {
      "type": "object",
      "javaType": "Address",
      "properties": {
        "street_address": { "type": "string" },
        "city":           { "type": "string" },
        "state":          { "type": "string" }
      },
      "required": ["street_address", "city", "state"]
    }
  },
  "type": "object",
  "properties": {
    "billing_address": { "$ref": "#/definitions/address" },
    "shipping_address": { "$ref": "#/definitions/address" }
  }
}

用两个文件回答

您需要在 Address.json 中使用javaType并使用$ref作为您的 billing_address 和送货地址。我建议您将地址定义分成一个单独的 json,然后在您的 billing_address 和 shipping_address 中使用它。


地址.json

{
    "$schema": "http://json-schema.org/draft-03/hyper-schema",
    "additionalProperties": false,
    "javaType": "whatever-package-name-you-have.Address"
    "type": "object",
    "properties": {
    "street_address": { "type": "string", "required":true},
    "city":           { "type": "string", "required":true },
    "state":          { "type": "string", "required":true }
  }
}

MainClass.json

{
    "$schema": "http://json-schema.org/draft-03/hyper-schema",
    "additionalProperties": false,
    "type": "object",
    "properties": {
     "billing_address": {
           "$ref":"Address.json",
           "type": "object",
           "required": false
          },
     "shipping_address": {
           "$ref":"Address.json",
           "type": "object",
           "required": false
          }
     }
}
于 2015-05-28T00:19:16.587 回答