我需要从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
和ShippingAddress
,即使这两个属性都引用了address
。因此,我宁愿同时拥有Address
类型的两个属性。
这可以用jsonschema2pojo实现吗?
答案 0 :(得分:3)
从here更好地了解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中使用它。
{
"$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 }
}
}
{
"$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
}
}
}