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

标签 c# .net-core jsonserializer system.text.json

我有一个私有(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/

相关文章:

c# - 将背景颜色应用于 GridView 中的所有标签

c# - 在 WPF 中高效地显示和缩放/平移大图像

.net - .NET 核心 Ubuntu 14.04 上的 System.Net 出现问题

json - 是否有与 JSON.NET(服务器端)良好集成并支持 "preserve references"功能的 JavaScript(客户端)JSON 库?

c# - 在 azure 应用服务中使用 Lucene.net 的最佳方法

c# - MemoryPool<T> 和 ArrayPool<T> 的区别

c# - 搜索日期范围内的票证字段

java - 如何将 JSON 映射到 java 模型类

ios - JSONSerialization.jsonObject 返回 nil

c# - 如何在 AfterReceiveRequest 中调用服务方法