包含另一个列表的列表的序列化

问题描述 投票:0回答:1

我想我的问题是关于(反)序列化一个类的列表,该类的列表本身具有一个列表属性,这给我带来了麻烦。 Lemme首先删除一些代码示例并进行解释。

我序列化的类是跟随的:

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());

当我打开序列化文件时,它对我来说看起来很完美,这是单元格#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?

c# json serialization collections deserialization
1个回答
0
投票

我建议您在Location结构中将JsonProperty从linkLocation更改为LinkData

[JsonProperty("linkLocation")]
public Point Location { get; }
© www.soinside.com 2019 - 2024. All rights reserved.