'收集尺寸为固定。'例外:System.Text.json.jsonserializer中的错误还是错误?
我已经研究了几个,所以回答了这个例外(例如这个)没有成功。另外,重现行为的示例是我看到的最小的。作为复制此问题的控制,我有一个常数的字符串:
const string json =
@"{
""ArrayOfString"": [""Hello World""]
}";
和 classa
:
class ClassA
{
public string[] ArrayOfString { get; set; }
}
没有问题 delelialization classa
是否使用<我做代码> newtonsoft.json 或 system.text.json
。
ClassA classA;
classA = Newtonsoft.Json.JsonConvert.DeserializeObject<ClassA>(json);
classA = System.Text.Json.JsonSerializer.Deserialize<ClassA>(json);
现在,考虑 classB
,其中同一属性具有 Baseclass
中的备份存储。
class ClassB : BaseClass
{
public string[] ArrayOfString
{
get => new string[] { base.SingularString };
set
{
if((value != null) && (value.Length == 1))
{
base.SingularString = value[0];
}
}
}
}
class BaseClass
{
public string SingularString { get; set; } = "Hello World";
}
从相同的 json
源中, classB
clastb 似乎并不是一个大的要求。
ClassB classB;
classB = Newtonsoft.Json.JsonConvert.DeserializeObject<ClassB>(json);
classB = System.Text.Json.JsonSerializer.Deserialize<ClassB>(json);
newtonsoft
没有任何牛肉这样做:
但是, system.text.json
当要求做同样的事情时抛出:
任何人是否有第一手知识此错误 2年前?这是重新出现的吗?还是只是犯某种错误?是的,我明白了。集合 是固定的尺寸,但这为什么重要?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个固定在.NET 5的错误。请参阅plup 替换收集实例#39442 。可以在这里看到一个工作.NET 6小提琴: https://dotnetfiddle.net/uhryjp 。
如果您必须针对.NET Core 3.1开发,则您的选项似乎包括:
为
classB
。使用
list&lt; string&gt;
而不是string []
arayofstring
:(请注意,如果您仍在定位System.Text.json和Newtonsoft,
list&lt; string&gt;
将无法与后者一起使用。请参阅Eg 当我的poco中的所有收藏都无效,当时将一些有效的json与.net newtonsoft.json component.json component P>This is a bug that was fixed in .NET 5. See pull Replace collection instances on deserialize #39442. A working .NET 6 fiddle can be seen here: https://dotnetfiddle.net/UhRYJP.
If you must develop against .NET Core 3.1, your options would appear to include:
Introduce a custom converter for
ClassB
.Use a
List<string>
instead of astring []
forArrayOfString
:(Note that if you are still targeting both System.Text.Json and Newtonsoft,
List<string>
will not work with the latter. See e.g. Why are all the collections in my POCO are null when deserializing some valid json with the .NET Newtonsoft.Json component for why.)