【问题标题】:Is it possible to find unmapped properties in System.Text.Json?是否可以在 System.Text.Json 中找到未映射的属性?
【发布时间】:2021-08-23 19:14:38
【问题描述】:

是否可以使用System.Text.Json.JsonSerializer 找到未映射的属性?

我正在访问一个返回文档数组的 API。我想知道是否有办法知道 json 文档中是否有我的 C# 类型未映射的属性。充其量是一个返回未映射属性列表的方法。

示例

JSON 文档

{
    "docs": [
        {
            "foo": "a",
            "bar": "b",
            "baz": "c",
        }
    ]
}

C# 类型

public class Wrapper 
{
    [JsonPropertyName("docs")]
    public List<MyDocument> Documents { get; set; }
}

public class MyDocument 
{
    [JsonPropertyName("foo")]
    public string Foo { get; set; }

    [JsonPropertyName("baz")]
    public string Baz { get; set; }
}

解析器

using System.Text.Json;

var body = "{ ... }";
var documents = JsonSerializer.Deserialize<Documents>(body);

List<JsonElement> unmappedProperties 
    = JsonSerializer.FindUnmappedProperties<Document>(body);

【问题讨论】:

标签: c# jsonserializer system.text.json


【解决方案1】:

您可以使用[JsonExtensionData],例如:

public class MyDocument 
{
    [JsonPropertyName("foo")]
    public string Foo { get; set; }

    [JsonPropertyName("baz")]
    public string Baz { get; set; }

    [JsonExtensionData]
    public Dictionary<string, object> ExtensionData { get; set; }
}

属性“bar”将被序列化为ExtensionData 属性。

您需要 .NET Core 3+ 或 .NET 5+(或 .NET framework 4.6.1 / NET Standard 2.0,请参阅 Jimi 的评论)

How to handle overflow JSON with System.Text.Json

要查找所有未映射的属性,您需要将带有[JsonExtensionData] 的属性添加到所有要序列化的类中。你也需要循环它(也许用反射)。虽然有点麻烦,但是很管用。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-02-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-30
相关资源
最近更新 更多