【发布时间】:2020-05-12 00:39:57
【问题描述】:
我想我的问题是关于(反)序列化一个类列表,它有一个属性本身就是一个列表,这给我带来了一些麻烦。让我先放一些代码示例并解释一下。
我序列化的类是follow:
public class Cell : ICell
{
#region ICell Implementation
[JsonProperty("ID")]
public int Id { get; set; }
[JsonProperty("Coordinates")]
public Coordinates Coordinates { get; set; }
[JsonProperty("IsHint")]
public bool IsHint { get; set; }
[JsonProperty("Number")]
public int Number { get; set; }
[JsonProperty("Points")]
public Point[] Points { get; set; }
[JsonProperty("Links")]
public List<LinkData> Links { get; set; }
#endregion
#region Constructor
[JsonConstructor]
public Cell(int id, int number, Coordinates coordinates, Point[] points, List<LinkData> links, bool isHint = false)
{
Id = id;
Number = number;
IsHint = isHint;
Coordinates = coordinates;
Links = links; // always empty !!!
Points = points;
}
// Code not serialized
}
序列化:
public void Save(string filePath)
{
using (var file = File.CreateText(filePath))
{
var serializer = new JsonSerializer
{
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
Formatting = Formatting.Indented,
PreserveReferencesHandling = PreserveReferencesHandling.None,
TypeNameHandling = TypeNameHandling.Auto
};
serializer.Serialize(file, board.Cells);
}
}
现在反序列化:
cells = JsonConvert.DeserializeObject<List<Cell>>(file.ReadToEnd());
当我打开序列化文件时,它看起来很完美,这里是 Cell #1:
{
"ID": 0,
"Coordinates": { "Coordinate": "0, -3" },
"IsHint": false,
"Number": 0,
"Points":
[
"813, 288",
"761, 318",
"709, 288",
"709, 228",
"761, 198",
"813, 228"
],
"Links":
[
{
"CellId1": 0,
"CellId2": 1,
"Location": "813, 258"
}
]
},
我的问题是,当这一行在反序列化时被实例化时,一切都很好,但“链接”的内容是空的。我的猜测是嵌套 List 需要更复杂的反序列化?
感谢您的帮助!
编辑:这是 LinkData 结构(必须这样做以避免解析单元溢出)的样子:
public struct LinkData
{
[JsonConstructor]
public LinkData(int cellId1, int cellId2, Point linkLocation)
{
CellId1 = cellId1;
CellId2 = cellId2;
Location = linkLocation;
}
[JsonProperty("CellId1")]
public int CellId1 { get; }
[JsonProperty("CellId2")]
public int CellId2 { get; }
[JsonProperty("Location")]
public Point Location { get; }
public static LinkData Empty => new LinkData(0, 0, Point.Empty);
}
编辑#2:
"Links":
[
{
"CellId1": 0,
"CellId2": 1,
"Location": "813, 258"
}
]
为什么Json部分代码没有变成List,为什么反序列化时为null?
【问题讨论】:
-
能否提供示例中的 LinkData 和 Points 对象结构?
-
编辑了我的帖子以显示 LinkData。 Points 只是一个常规的 System.Drawing.Point 数组,我在其中存储了绘制单元格的点(在我的例子中是一个正六边形)。
-
linkLocation和location一样吗?如果将linkLocation更改为location会发生什么? -
不,不幸的是,将两者都设置为位置会导致同样的问题。
-
你能告诉我
LinkData构造函数在你做了我建议的改变吗?另外,请提及@myname,否则它不会通知我您的评论。另外,您是否在构造函数中放置了断点?断点被命中了吗?
标签: c# json serialization collections deserialization