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



我有一个对象作为Json Schema(JSchema)的属性。

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

然而,当它被序列化时:

string str = JsonConvert.SerializeObject(foo); 

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

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

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

你会怎么做?

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

小提琴手: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;

小提琴手:https://dotnetfiddle.net/FwJX69

相关内容

  • 没有找到相关文章

最新更新