3

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.

2
  • what about using 'dynamic' ? Commented Mar 9, 2016 at 20:04
  • @Marty since schema might be arbitrary i would think that it can be create like dynamic object or i dont know Jobject instance or whatever even string, or what s your question ? Commented Mar 9, 2016 at 20:06

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

10 Comments

no , my intent is not get c# class code in order to compile, i want in runtime on any given vaiild json schema produce json object from it with default values, so im looking for lib or api in json.net, i will update my question to make it clear sorry
what would the defaults be ? a dynamic object, with props from schema set to NULL values ?
null in case schema not specified default value for property , if it specified default value then it should be there , check node package from reference in question ,it does what i want in javascript
yep, working on it. seems that there is no out of the box solution. at least from NewtonSoft
thanks for looking into it!, i checked source code of js lib - seems not too big, and might be rewritten in c# but still:)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.