Matt27
Matt27

Reputation: 325

How to validate multiple $ref in a JsonSchema type property

I am wanting to use a Json Schema to validate some incoming Json on a restful web service. But I'm having issues with using multiple $ref's in the type property of the schema.

I need to be able to do this:

"type" : [ {"$ref" : "#myObjectRef"}, {"$ref" : "#otherRef"} ]

i.e. the object must conform to one of the schemas referenced.

But when I run this through Json.Net using JsonSchema.Parse I get the following error: "Exception JSON schema type string token, got Array"

I get exactly the same error when trying this Json Schema for a statement from the TinCan Api through the Json.Net validator. But the json schema validates against JsonSchema Lint.

How can Json.Net handle having multiple type options in the schema? Is there an alternative .net library which will do this validation?

Upvotes: 3

Views: 2129

Answers (1)

Jason Desrosiers
Jason Desrosiers

Reputation: 24479

The type field in a JSON Schema must be a either a string or an array of unique strings. These strings can be any of the JSON primitives.

  • array
  • boolean
  • integer
  • number
  • null
  • object
  • string

What you need is the oneOf field.

{
    "oneOf": [{"$ref": "#myObjectRef"}, {"$ref": "#otherRef"}]
}

This schema enforces that the object must conform to one (and only one) of the two schemas referenced. If matching both schemas is also valid, you can use anyOf instead.

References

Upvotes: 6

Related Questions