【发布时间】:2022-11-27 09:28:08
【问题描述】:
我有一个这样的类,我想序列化和反序列化
using Newtonsoft.Json;
TestClass testClass = new TestClass();
testClass.Foo = "Foo";
testClass.Bar[0] = 3;
// to JSON
string json = JsonConvert.SerializeObject(testClass);
// and back
TestClass result = JsonConvert.DeserializeObject<TestClass>(json)!;
/// <summary>
/// External class that I cannot change
/// </summary>
public class TestClass
{
public string Foo { get; set; }
public int[] Bar { get; } = new int[3];
}
序列化效果很好,但在反序列化时“Bar”不可写,因此被跳过并具有默认值。 有没有办法告诉 Json.net 逐个元素反序列化(可能是真正的数组?)数组并将其设置为相应数组索引的值?
【问题讨论】:
-
我想到了两种方法:(1) 在 TestClass 中声明一个构造函数(与
[JsonConstructor]属性一起使用时可以是私有的),它允许反序列化器将反序列化的数组传递到 TestClass 实例中。然后,您还需要声明一个公共参数构造函数。 (2) 使用 List<int> 而不是 int[]。由您选择一个与项目的整体代码设计更匹配的... -
我没有机会改变 TestClass。它是外部库的一部分
-
好吧。那么我会同意下面 BWA 的回答中给出的建议。 (我很抱歉忽略了之前代码示例中的相应代码注释。)