JSON.net反序列化对null的引用

时间:2016-03-11 16:27:45

标签: c# json json.net deserialization

我有一个以#ProductParts为对象的C#应用​​程序,一个Part可以包含一个或多个子ProductPart。但是,零件也可以间接方式包含对其他零件的引用。

class ProductPart
{
    List<ProductPart> ProductParts;
    ProductPart MaterialReference { get; set; }
    ProductPart ColorReference { get; set; }
    ProductPart ActiveStateReference { get; set; }
}

我使用JSON.net来保存/加载这些部件。但是,我注意到某些引用存在问题。

这是一个精简的JSON文件示例来演示我的问题。

{
  "$id": "3",
  "Name": "ProductName",
  "ProductParts": {
    "$id": "5",
    "$values": [
      {
        "$id": "6",
        "Name": "top",
        "ProductParts": {
          "$id": "8",
          "Name": "bottom",
          "$values": [
            {
              "$id": "9",
              "MaterialReference": {
                "$ref": "6"
              },
              "ColorReference": {
                "$ref": "6"
              },
              "ActiveStateReference": {
                "$ref": "6"
              }
            }
          ]
        }
      }
    ]
  }
}

当我将这样的文件加载到我的应用程序中时,Reference字段为null。这是因为我在这里创建了一个参考循环吗?我试图通过使用

让JSON.net在这种情况下抛出错误
  

ReferenceLoopHandling = ReferenceLoopHandling.Error

但令我惊讶的是,这不会引发错误。我创建了一个无法解析的数据结构吗?

1 个答案:

答案 0 :(得分:0)

您需要删除班级中的循环引用。像这样创建一个Mapping类结构来反序列化Json

    class ProductPart
    {
        [JsonProperty("$id")]
        public int Id { get; set; }
        public string Name { get; set; }
        [JsonProperty("ProductParts")]
        List<ProductPartsA> ProductPartsA;
    }

    class ProductPartsA
    {
        [JsonProperty("$id")]
        public int Id { get; set; }
        public string Name { get; set; }
        [JsonProperty("ProductParts")]
        List<ProductPartsB> ProductPartsB;
    }

    class ProductPartsB
    {
        [JsonProperty("$id")]
        public int Id { get; set; }
        public string Name { get; set; }
        [JsonProperty("$values")]
        List<Values> Values;
    }

    class Values
    {
        [JsonProperty("$id")]
        public int Id { get; set; }
        public Reference MaterialReference { get; set; }
        public Reference ColorReference { get; set; }
        public Reference ActiveStateReference { get; set; }
    }

    class Reference
    {
        [JsonProperty("$ref")]
        public string Ref { get; set; }
    }

显然,这可以通过继承处理得更好,但你明白了。然后,您可以通过以下方式反序列化您的json:

var myClass = JsonConvert.DeserializeObject<ProductPart>(jsonstr);