I would like to be able to dynamically create valid reference data using a JSON schema, I'm not sure if there is something built into NewtonSoft.JSON for this or not, or if there is some combination of classes and methods I could use to easily generate the appropriate JSON.
I've been tinkering with this over the past few days and this is what I have thus far.
CreateJson
static void CreateJson(KeyValuePair<string, JSchema> jsonProperty, JObject jObject)
{
switch (jsonProperty.Value.Type)
{
case JSchemaType.Array:
jObject.Add(new JProperty(jsonProperty.Key, new JArray()));
foreach (var jItem in jsonProperty.Value.Items)
{
foreach (var jProp in jItem.Properties)
{
CreateJson(jProp, jObject);
}
}
break;
case JSchemaType.Object:
JObject nestedObject = new JObject();
foreach (var jProp in jsonProperty.Value.Properties)
{
CreateJson(jProp, nestedObject);
}
jObject.Add(new JProperty(jsonProperty.Key, nestedObject));
break;
default:
jObject.Add(new JProperty(jsonProperty.Key, jsonProperty.Value.Default));
break;
}
}
It gets called like this
example
JSchema schema = JSchema.Parse(jsonSchema);
JObject jsonObject = new JObject();
foreach (var prop in schema.Properties)
{
CreateJson(prop, jsonObject);
}
The output is a little wonky though
{{
"checked": false,
"dimensions": {
"width": 0,
"height": 0
},
"id": 0,
"name": "",
"price": 0,
"tags": []
}}
First it appears there is the double braces, which I'm not 100% certain where they came from. The next is that Dimensions is an object with Width and Height as properties, they are not nested inside the Dimensions object. For this POC I know exactly what and where they should be, but in production the code won't "know" anything about the schema coming in. I feel I'll have a similar problem with the array, but not sure that actually worked as the array is just strings, and I was more interested in the object.
I was looking at this example on Newtonsoft.com but again that sample knows exactly where the thing is they want to find. I am almost wondering if when the code encounters an object it should handle it differently...or perhaps the default switch that is capturing the individual properties is wrong.
Any advice is again very much appreciated.