如何将$ ref添加到JSONSchema?

时间:2012-01-08 19:27:34

标签: c# json json.net jsonschema

我有一个JSONSchema,它有一些项目。现在定义这些项的模式需要在主模式中引用吗?

* one schema that you reference:
 { 
    "id": "http://some.where/sub/schema#", 
    "type": "object", 
    "properties": { 
        "p1": { 
            "type": "integer", 
            "minimum": 12 
        } 
    }     
} 
--- * the main schema: ---- 
{ 
    "id": "http://path.to/base/schema#", 
    "type": "array", 
    "items": { 
        "extends": { 
            "$ref": "http://some.where/sub/schema#/properties/p1" 
        }, 
        "divisibleBy": 5 
    }     
} 

另请注意,我的项目中会包含多个项目。我没有看到在api中这样做的方法。 api也不允许我添加自定义属性。我怎样才能实现这一目标?我正在使用 JSON.net

1 个答案:

答案 0 :(得分:3)

由于评论时间过长,我会将其作为答案发布。但你应该根据自己的需要进行定制。

string oneSchema = @"{ 
    ""id"": ""http://some.where/sub/schema#"", 
    ""type"": ""object"", 
    ""properties"": { 
        ""p1"": { 
            ""type"": ""integer"", 
            ""minimum"": 12 
        } 
    }     
} ";

string main = @"
{ 
    ""id"": ""http://path.to/base/schema#"", 
    ""type"": ""array"", 
    ""items"": { 
        ""extends"": { 
            ""$ref"": ""http://some.where/sub/schema#/properties/p1"" 
        }, 
        ""divisibleBy"": 5 
    }     
}";

var JObjMain = (JObject)JsonConvert.DeserializeObject(main);
var jObjOther = (JObject)JsonConvert.DeserializeObject(oneSchema);

JToken src = JObjMain["items"]["extends"]["$ref"];
JToken reference = jObjOther["id"];


var path = src.ToString().Replace(reference.ToString(), "").Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
JToken j = jObjOther[path[0]];
for(int i=1;i<path.Length;i++)
{
    j = j[path[i]];
}

src.Replace(j);

Console.WriteLine(JObjMain);