我有一个使用 Json.Net 序列化的类。我最近需要添加一个 Color
类的属性以及在构造函数中设置它的好方法。
public class InfoClass
{
public static Color DefaultColor = Color.SlateBlue;
public String Name { get; set; }
public int Left { get; set; }
public int Right { get; set; }
public Color ColorId { get; set; }
public InfoClass(String name, int left, int right)
{
Name = name;
Left = left;
Right = right;
ColorId = DefaultColor;
}
public InfoClass(String name, int left, int right, Color colorId)
{
Name = name;
Left = left;
Right = right;
ColorId = colorId;
}
}
我发现,一旦添加第二个构造函数,我就会在我的 Application.Run
处抛出异常(我很确定是反序列化此类的结果)。在Program.cs
。这是一个TargetInvocationException
内部异常(exception) NullReferenceException
。内部异常还指出 Data
是 System.Collections.ListDictionaryInternal
,我持有 List<InfoClass>
在我正在序列化的类(class)中。
由于在添加此构造函数之前一切正常,我必须假设错误就在其中,尽管我不确定为什么?
仅作为 List<InfoClass>
序列化时的引用Json.Net 生成以下 Json
"InfoList": [
{
"Name": "One",
"Left": 1,
"Right": 2,
"ColorId": "SlateBlue"
},
{
"Name": "Two",
"Left": 3,
"Right": 4,
"ColorId": "SlateBlue"
}]
我还查看了this SO answer其中讨论了序列化 Color
的正确方法。我已经实现了这项技术,并简单地保存了 Color
作为它的 RGB 值。所有这些方法都可以序列化数据,但在反序列化时我仍然遇到相同的异常。尽管如果构造函数不存在,我不会收到这些方法的错误。所以我完全确信它就是这个构造函数(但我之前就错了)。
编辑:在突然清晰的片刻之后,我在反序列化调用周围放置了一个 try/catch 并发现异常返回了消息
Unable to find a constructor to use for type [InfoClass]. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute.
我猜 Json.Net 不喜欢没有默认值或没有标记的多个构造函数。
最佳答案
创建一个无参数构造函数并使用 [JsonConstructor]
属性对其进行注释。
public class InfoList
{
[JsonConstructor]
public InfoList()
{
}
/* your other constructors here */
}
如果没有你的 json 示例,我无法真正测试,但我之前在使用多个构造函数时遇到过这个问题。
编辑:看起来您刚刚找到了同样的东西。
关于c# - 添加第二个采用 Color 类型参数的构造函数时,Json.Net 会起作用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36263394/