我需要从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

但是,即使两个属性都引用了BillingAddress,它也会生成两个单独的类ShippingAddressaddress。因此,我宁愿同时拥有Address类型的两个属性。

使用jsonschema2pojo是否可以实现?

最佳答案

更新资料

here更好地了解javaType之后。通过在您的Address定义中添加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,并为$ billing_address和送货地址使用$ ref。我建议您将地址定义分成单独的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
          }
     }
}

09-28 03:45