Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create default json object from json schema in c#

I can not google that thing on json.net api reference or anywhere. I want to create object from json schema with default values filled in. Basically some thing like this:

var JsonSchema=JsonSchema.ReadSchemaFromSomeWhere();
dynamic DefaultObject= JsonSchema.GetDefaultObject();

Example you might see in json-schema-defaults package.

Example

var JsonSchema=JsonSchema.ReadSchemaFromString("
{
  "title": "Album Options",
  "type": "object",
  "properties": {
    "sort": {
      "type": "string",
      "default": "id"
    },
    "per_page": {
      "default": 30,
      "type": "integer"
    }
  }");

dynamic DefaultObject= JsonSchema.GetDefaultObject();

//DefaultObject dump is
{
  sort: 'id',
  per_page: 30
}

UPDATE

I want lib or api in json.net to create object with default values from any given valid json schema during runtime.

like image 441
Kostia Mololkin Avatar asked Jan 19 '26 07:01

Kostia Mololkin


1 Answers

Well a simple case might be this

[Test]
public void Test()
{
   dynamic ob = new JsonObject();
   ob["test"] = 3;

   Assert.That(ob.test, Is.EqualTo(3));

}

I used the RestSharp library that provides a good dynamic implementation that allows indexing ["test"];

So then - what You're left to do is read the properties from the schema and assign values (of course this will work only for simple plain case`s, but might be a start

dynamic ob = new JsonObject();
foreach (var prop in JsonSchema.Properties)
{

   if (prop.Default != null)
      ob[prop.Name] = prop.Default
}
like image 104
Marty Avatar answered Jan 20 '26 22:01

Marty