【问题标题】:How do i serialize a JSchema as part of another object?如何将 JSchema 序列化为另一个对象的一部分?
【发布时间】:2016-04-15 00:28:49
【问题描述】:

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

JSchema aSchema;

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

但是,当它被序列化时:

string str = JsonConvert.SerializeObject(foo); 

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

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

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

你会怎么做?

【问题讨论】:

  • 查看您当前获得的输出有助于更好地理解问题。
  • 放上你的 JSON Schema 类或者放上你想要的输出。

标签: json.net jsonschema


【解决方案1】:
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

【讨论】:

  • 我了解如何从上面显示的自定义对象创建 Json 输出。但是,正如我在帖子中提到的,我正在使用具有许多其他属性等的 JSchema 对象...
  • 放上你的 JSON Schema 类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-10
相关资源
最近更新 更多