如何将JSchema序列化为另一个对象的一部分?

时间:2016-04-15 00:28:50

标签: json.net jsonschema

我有一个对象,它是一个Json Schema(JSchema)的属性。

string str = JsonConvert.SerializeObject(foo); 

但是,当序列化时:

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

JSchema对象与其所有其他属性一起被序列化......而不是一个干净的Json Schema,就像它的ToString()的输出一样,它只发出Json Schema字符串。

我想要的是作为Json Schema对象序列化的schema属性,如下所示:

.env

你会怎么做?

1 个答案:

答案 0 :(得分:0)

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; }
}

序列化方法

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

<强>更新

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