pmeyer pmeyer - 11 months ago 55
C# Question

Why are my array objects are of type "type": ["object","null"] when generating a JsonSchema

So, I have a class defined as such...

public class foo
{
public List<bar> Bars {get;set;}
}

public class bar
{
public string foorbar {get;set;}
}


When I use the
JsonSchemaGenerator
to generate its schema I get the following output...

var generator = new JsonSchemaGenerator();
return generator.Generate(typeof(foo), false);

{
"type": "object",
"properties" : {
"Bars":{
"type": "array",
"items": {
"type": ["object","null"],
"properties": {
"foorbar":{"type":"string"}
}
}
}
}
}


So, why are my items inside the array of type
"type": ["object","null"]


I believe this is causing issues, how can I remove the nullable object type here?

Thanks

Answer Source

The scheme allows null because you could do something like this and try to serialize it, which is perfectly valid on the C# side:

myFoo.Bars.Add(null);

To disallow null values in JSON side of the array, add the JsonArrayAttribute to the array member (Bars), like this:

[JsonArray(false)]
public List<bar> Bars {get;set;}

Details can be found here.

I was led to this attribute by looking at the source code of JsonSchemaGenerator, specifically, line 285.