我想使用JSON Schema并允许新类型(目前有string、number、array、object、boolean和null)
例如,我想为联系人添加一个类型
这在JSON中是可能的吗?有什么建议吗?
谢谢
发布于 2014-11-23 23:11:38
如果您的目标是定义一次contact并多次重用它,那么您可以为一个名为contact的object创建一个定义,然后在需要时使用contact指针引用它。
其中一个示例可能如下所示:
{
"type": "object",
"definitions": {
"contact": {
"properties": {
"name": {
"type": "string"
},
"phone": {
"type": "string"
}
}
}
},
"properties": {
"Person": {
"properties": {
"contact": {
"$ref" : "#/definitions/contact"
},
"birthday": {
"type": "string",
"format": "date-time"
}
}
},
"Company": {
"properties": {
"contact": {
"$ref" : "#/definitions/contact"
},
"inBusinessSince" : {
"type": "string",
"format": "date-time"
}
}
}
}
}现在假设您希望Company的contact属性比Person属性具有更多的属性。您可以使用allOf关键字,以便上面的公司现在看起来如下所示:
"Company": {
"properties": {
"contact": {
"allOf": [
{"$ref" : "#/definitions/contact"},
{
"properties": {
"fax": {
"type": "string"
}
}
],
"inBusinessSince" : {
"type": "string",
"format": "date-time"
}
}
}有关更多信息,请参阅以下链接。
发布于 2012-11-19 21:04:50
是的,我们可以在JSON中为联系人添加类型
假设您的程序需要以下格式的联系人类型数据
{
contact: [
{contactid:1, contactname: "abc", address:"abcdfg"},
{contactid:2, contactname: "hjk", address:"hjkdfg"}
]
}这里的Contact对象有一个id、名字和地址。我们可以为联系人创建一个架构
{
"type" : "object",
"properties": {
"contact":{
"type":"object"
"items":{
"type": "object",
"properties":{
"contactid": {"type":"number"}
"contactname": {"type":"string"}
"address": {"type":"string"}
}
}
}
}
} 发布于 2012-11-19 20:51:31
"contact“的类型应该是object类型,不是吗?然后这个对象有几个属性,例如一个包含地址的字符串。所以根本不需要定义新类型,因为每个新类型都由基本类型string、number、array或object组成。
因此,对于联系人,您可以这样写:
"contact"{
"id": "contact",
"required": false,
"type": "object",
"properties":{
"address"{
"id": "address",
"required": true,
"type": "string"
}
"phoneNumbers"{
"id": "phoneNumbers",
"required": false,
"type": "array",
"items":{
"id": "0",
"required": false,
"type": "object",
"properties":{
"type"{
"id": "type",
"required": false,
"type": "string"
}
"number"{
"id": "number",
"required": false,
"type": "string"
}
}
}
}
}
}根据这个模式,一个简单的联系人对象可能看起来像这样:
{
"address": "Example Street 123",
"phoneNumbers":
[
{
"type": "home",
"number": "123-456789"
}
]
} 现在假设您在另一个对象中有多个联系人,那么您必须在存储联系人的每个位置添加联系人模式。
如上所述,我不认为有任何需要引入新类型,尽管您的模式可能会变得非常非常大。除此之外,我不知道任何允许新原语类型的JSON模式规范。
https://stackoverflow.com/questions/13453631
复制相似问题