System.Text.Json.JsonSerializer可以在只读属性上序列化集合吗? [英] Can System.Text.Json.JsonSerializer serialize collections on a read-only property?

查看:322
本文介绍了System.Text.Json.JsonSerializer可以在只读属性上序列化集合吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在获取新的System.Text.Json来反序列化存储在只读属性上的集合时遇到了麻烦.

I'm having trouble getting the new System.Text.Json to deserialize collections stored on read-only properties.

请考虑以下课程:

public class SomeItem {
    public string Label { get; set; }
}

public class SomeObjectWithItems {

    public string Label { get; set; }

    // Note this property is read-only but the collection it points to is read/write
    public ObservableCollection<SomeItem> Items { get; }
        = new ObservableCollection<SomeItem>();
}

这是JSON:

{
  "Label": "First Set",
  "Items": [
    {
      "Label": "Item 1"
    },
    {
      "Label": "Item 2"
    },
    {
      "Label": "Item 3"
    },
    {
      "Label": "Item 4"
    }
  ]
}

这是我正在运行的代码...

Here's the code I'm running...

var json = ...;
var obj = JsonSerializer.deserialize<SomeObjectWithItems>(json);
Debug.WriteLine($"Item Count for '{obj.label}': {obj.Items.Count}");  

上面的输出如下:

Item Count for 'First Set': 0

如果我将Items更改为可读写,那么它可以工作,但是我们的许多模型都有只读属性,这些属性保存可变的集合,所以我想知道我们是否可以使用它.

If I change Items to be read/write, then it works, but so many of our models have read-only properties that hold mutable collections so I'm wondering if we can even use this.

注意:Json.NET正确处理了此问题,在现有集合上内部调用了"Add"方法,而不是创建一个新方法,但是我不知道如何为我们编写的所有类编写自定义转换器之外的方法已经定义.

Note: Json.NET handles this correctly, internally calling the 'Add' method on the existing collection rather than creating a new one, but I don't know how to achieve that outside of writing custom converters for all the classes we have defined.

推荐答案

这是为没有二传手的集合设计的.避免 添加到预填充集合中的问题(该序列化程序 不实例化)反序列化器使用替换"语义 要求该集合具有二传手.

This is by design for collections that don't have a setter. To avoid issues with adding to pre-populated collections (that the serializer doesn't instantiate) the deserializer uses "replace" semantics which requires the collection to have a setter.

来源: https://github.com/dotnet/corefx/issues/41433

Support adding to collections if no setter

https://github.com/dotnet/corefx/issues/39477

在这种情况下,我的建议是继续使用Json.NET,除非您要编写客户转换器.

My recommendation is continue to use Json.NET in this case unless you want to write a customer converter.

这篇关于System.Text.Json.JsonSerializer可以在只读属性上序列化集合吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆