【发布时间】:2020-02-22 06:59:16
【问题描述】:
我希望能够在使用 System.Text.Json.JsonSerializer 进行序列化时排除属性。我不想在任何我想这样做的地方使用JsonIgnore 属性。我希望能够通过某种目前不存在的 Fluent API 来定义我想在序列化期间排除的属性。
我能找到的唯一选择是定义一个 JsonConverter 并将其添加到 JsonSerializerOptions 上的转换器列表中,我将其传递给 Serialize() 方法,如下所示:
var options = new JsonSerializerOptions();
options.Converters.Add(new BookConverter());
json = JsonSerializer.Serialize(book, options);
在 JsonConverter 中,我必须自己使用 Utf8JsonWriter 编写整个 JSON 表示,不包括我不想序列化的属性。仅仅能够排除一个属性需要做很多工作。虽然 JsonConverter 是 .NET 团队的一项出色的可扩展性功能,但对于我的用例而言,它的级别太低了。有谁知道无需自己写出 JSON 表示即可排除该属性的任何其他方法?
我不想做以下事情:
- 使用属性,或在运行时动态添加属性
- 将属性的访问修饰符更改为
private或protected - 使用 3rd 方库,因为如果我使用 Json.NET,我的问题是可以解决的。
例子:
class Program
{
void Main()
{
// We want to serialize Book but to ignore the Author property
var book = new Book() { Id = 1, Name = "Calculus", Author = new Author() };
var json = JsonSerializer.Serialize(book);
// Default serialization, we get this:
// json = { "Id": 1, "Name": "Calculus", "Author": {} }
// Add our custom converter to options and pass it to the Serialize() method
var options = new JsonSerializerOptions();
options.Converters.Add(new BookConverter());
json = JsonSerializer.Serialize(book, options);
// I want to get this:
// json = { Id: 1, Name: "Calculus" }
}
}
public class Author { }
public class Book
{
public int Id { get; set; }
public string Name { get; set; }
public Author Author { get; set; }
}
public class BookConverter : JsonConverter<Book>
{
public override Book Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
// Use default implementation when deserializing (reading)
return JsonSerializer.Deserialize<Book>(ref reader, options);
}
public override void Write(Utf8JsonWriter writer, Book value, JsonSerializerOptions options)
{
// Serializing. Here we have to write the JSON representation ourselves
writer.WriteStartObject();
writer.WriteNumber("Id", value.Id);
writer.WriteString("Name", value.Name);
// Don't write Author so we can exclude it
writer.WriteEndObject();
}
}
【问题讨论】:
标签: c# json serialization .net-core