Chris Johnson
Chris Johnson

Reputation: 1340

How do i serialize a JSchema as part of another object?

I have an object who as a property that is a Json Schema (JSchema).

JSchema aSchema;

object foo = new {propA = "x", schema =  aSchema};

However, when this is serialized:

string str = JsonConvert.SerializeObject(foo); 

The JSchema object is serialized along with all its other properties ... and not a clean Json Schema, like the output of its ToString() which just emits the Json Schema string.

What I want is the schema property serialized as a Json Schema object like this:

{
    "propA": "x",
    "schema": {
        "id": "",
        "description": "",
        "definitions": {
            "number": {
                "type": "number"
            },
            "string": {
                "type": "string"
            }
        },
        "properties": {
            "title": {
                "title": "Title",
                "type": "string"
            }
        }
    }
}

How would you do this?

Upvotes: 1

Views: 450

Answers (1)

Krunal Mevada
Krunal Mevada

Reputation: 1655

public class Number
{
    public string type { get; set; }
}
public class String
{
    public string type { get; set; }
}
public class Definitions
{
    public Number number { get; set; }
    public String @string { get; set; }
}
public class Title
{
    public string title { get; set; }
    public string type { get; set; }
}
public class Properties
{
    public Title title { get; set; }
}
public class Schema
{
    public string id { get; set; }
    public string description { get; set; }
    public Definitions definitions { get; set; }
    public Properties properties { get; set; }
}
public class RootObject
{
    public string propA { get; set; }
    public Schema schema { get; set; }
}

Serialize method

dynamic coll = new
{
    Root = new RootObject()
    {
        propA = "x",            
        schema = new Schema
        {   
            id = "",
            description = "",
            definitions = new Definitions()
            {
                number = new Number()
                {
                    type = "number"
                },
                @string  = new String()
                {
                    type = "number"
                }
            },
            properties = new Properties ()
            {
                title = new Title ()
                {
                    title = "Title",
                    type = "string"
                }
            }
        }
    }
};

var output = JsonConvert.SerializeObject(coll);

Fiddler: https://dotnetfiddle.net/f2wG2G

Update

var jsonSchemaGenerator = new JsonSchemaGenerator();
var myType = typeof(RootObject);

var schema = jsonSchemaGenerator.Generate(myType);
schema.Id = "";
schema.Description = "";
schema.Title = myType.Name;

Fiddler: https://dotnetfiddle.net/FwJX69

Upvotes: 0

Related Questions