gpt4 book ai didi

c# - 获取 .NET Core JsonSerializer 以序列化私有(private)成员

转载 作者:行者123 更新时间:2023-12-04 02:35:54 26 4
gpt4 key购买 nike

我有一个私有(private)类(class)List<T>我想使用 JsonSerializer 序列化/反序列化的属性.使用 JsonPropertyAttribute .NET Core 似乎不支持。那么我怎样才能序列化我的私有(private)列表属性呢?

我为此使用 System.Text.Json。

最佳答案

似乎 System.Text.Json 不支持私有(private)属性序列化。

https://docs.microsoft.com/tr-tr/dotnet/standard/serialization/system-text-json-migrate-from-newtonsoft-how-to#internal-and-private-property-setters-and-getters

但正如微软的文档所说,您可以使用自定义转换器来做到这一点。

https://www.thinktecture.com/en/asp-net/aspnet-core-3-0-custom-jsonconverter-for-the-new-system_text_json/

序列化的代码片段;

  public class Category
{
public Category(List<string> names)
{
this.Names1 = names;
}

private List<string> Names1 { get; set; }
public string Name2 { get; set; }
public string Name3 { get; set; }
}


public class CategoryJsonConverter : JsonConverter<Category>
{
public override Category Read(ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options)
{
var name = reader.GetString();

var source = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(name);

var category = new Category(null);

var categoryType = category.GetType();
var categoryProps = categoryType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

foreach (var s in source.Keys)
{
var categoryProp = categoryProps.FirstOrDefault(x => x.Name == s);

if (categoryProp != null)
{
var value = JsonSerializer.Deserialize(source[s].GetRawText(), categoryProp.PropertyType);

categoryType.InvokeMember(categoryProp.Name,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetProperty | BindingFlags.Instance,
null,
category,
new object[] { value });
}
}

return category;
}

public override void Write(Utf8JsonWriter writer,
Category value,
JsonSerializerOptions options)
{
var props = value.GetType()
.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.ToDictionary(x => x.Name, x => x.GetValue(value));

var ser = JsonSerializer.Serialize(props);

writer.WriteStringValue(ser);
}
}

static void Main(string[] args)
{
Category category = new Category(new List<string>() { "1" });
category.Name2 = "2";
category.Name3 = "3";

var opt = new JsonSerializerOptions
{
Converters = { new CategoryJsonConverter() },
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};

var json = JsonSerializer.Serialize(category, opt);

var obj = JsonSerializer.Deserialize<Category>(json, opt);

Console.WriteLine(json);
Console.ReadKey();
}

结果;
"{\"Names1\":[\"1\"],\"Name2\":\"2\",\"Name3\":\"3\"}"

关于c# - 获取 .NET Core JsonSerializer 以序列化私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61869393/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com