【问题标题】:Replacing System.Text.Json with Manatee.Json for serialization in .NET Core 3用 Manatee.Json 替换 System.Text.Json 以在 .NET Core 3 中进行序列化
【发布时间】:2020-05-08 09:32:04
【问题描述】:

背景
我想从我的 .NET Core 3 应用程序中提供一些 JsonSchema,以及序列化为 JSON 的其他对象。由于 Manatee.Json 经常更新并为 JsonSchema 提供了良好的支持,因此它们是我的首选。同时,.NET Core 3 为返回对象提供了出色的支持,可以将对象转换为 JSON 文档。

例子:

public ActionResult<MyFancyClass> MyFancyAction()
{
    return new MyFancyClass {
        Property1 = "property 1 content",
        Property2 = "property 2 content",
    };
}

输出:

{
    "Property1": "property 1 content",
    "Property2": "property 2 content"
}

问题
.NET Core 3 具有对 JSON 的内部支持,其 System.Text.Json 在前面的示例中使用。如果我尝试序列化Manatee.Json.Schema.JsonSchema,它的内部结构是序列化的,而不是json模式本身。

例子:

public ActionResult<MyFancyClass2> MyFancyAction2()
{
    return new MyFancyClass2 {
        Property1 = "property 1 content",
        Property1Schema = new JsonSchema()
            .Type(JsonSchemaType.String)
    };
}

输出:

{
  "Property1": "property 1 content",
  "Property1Schema": [{
    "name":"type",
    "supportedVersions":15,
    "validationSequence":1,
    "vocabulary": {
      "id":"https://json-schema.org/draft/2019-09/vocab/validation",
      "metaSchemaId":"https://json-schema.org/draft/2019-09/meta/validation"
    }
  }]
}

我希望这样:

{
  "Property1": "property 1 content",
  "Property1Schema": {
    "type": "string",
  }
}

Manatee.Json.JsonValue 也有一个冲突的内部结构,其中System.Text.Json.JsonSerializer 无法正确访问内部 get 方法,例如我收到以下异常消息:

Cannot access value of type Object as type Boolean.

发现
Manatee.Json.Schema.JsonSchema 有一个 .ToJson() 方法,可用于获取正确的 json 架构为 JsonValue,但随后我遇到了我刚才提到的序列化问题Manatee.Json.JsonValue.

问题
有谁知道将 .NET Core 3 中的默认序列化从使用 System.Text.Json 更改为使用 Manatee.Json 的方法?

Sidemark
另一种方法是启用System.Text.Json 序列化Manatee.Json 结构(看看this question)。

【问题讨论】:

    标签: json .net-core .net-core-3.0 system.text.json manatee.json


    【解决方案1】:

    你很幸运!我只是将模式继任者发布给 Manatee.Json:JsonSchema.Net!它完全支持草案 6 到 2019-09,100% 基于 System.Text.Json,而且速度快得离谱!

    希望这会有所帮助。

    (不知道为什么我没有收到Manatee.Json 标签的电子邮件。抱歉花了这么长时间才找到这个。)

    【讨论】:

    • 非常感谢 :) 到目前为止,我一直在使用 JsonConverter&lt;JsonValue&gt; 实现和 JsonConverter&lt;JsonSchema&gt; 实现。 JsonSchemaConverterJsonSchema 转换为JsonValue,在其转换器将其序列化为字符串,然后是JsonDocument,最后是JsonElement。很长的路要走,但它有效:) 我绝对会尝试JsonSchema.Net =)
    猜你喜欢
    • 2020-05-08
    • 2020-01-26
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    相关资源
    最近更新 更多