ashutosh raina
ashutosh raina

Reputation: 9314

How do i add $ref to a JSONSchema?

I have a JSONSchema which will have some items . Now the schema/s that define those items need to be referred in the main schema ?

* 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 
    }     
} 

Also note , i will have multiple items in the item . I do not see a way of doing this in the api . Nor does the api allow me to add custom properties . How can i achieve this ? I am using JSON.net.

Upvotes: 1

Views: 1753

Answers (1)

L.B
L.B

Reputation: 116168

Since It will be too long for a comment, I'll post it as an answer. But You should work on it to customize according to your needs.

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);

Upvotes: 3

Related Questions