首页 > 解决方案 > JSON .NET 不反序列化 Refs

问题描述

我有以下最小示例:

class Program
    {
        static void Main()
        {
            var plan = new Plan
            {
                Steps =
                {
                    new Step
                    {
                        Contexts =
                        {
                            new Context
                            {
                                Name = "1"
                            },
                            new Context
                            {
                                Name = "2"
                            }
                        }
                    }
                }
            };

            var settings = new JsonSerializerSettings
            { PreserveReferencesHandling = PreserveReferencesHandling.Objects, Formatting = Formatting.Indented };
            var json = JsonConvert.SerializeObject(plan, settings);
            var deserialized = JsonConvert.DeserializeObject<Plan>(json, settings);

        }
    }

    class Plan
    {
        public IEnumerable AllContexts => Steps.SelectMany(i => i.Contexts);
        [JsonProperty(Order = int.MaxValue)]
        public ICollection<Step> Steps { get; set; } = new List<Step>();
    }

    class Step
    {
        public ICollection<Context> Contexts { get; set; } = new List<Context>();
    }

    class Context
    {
        public string Name { get; set; }
    }

在此示例deserialized中,反序列化时已丢失其引用,并且deserialized.AllContexts是 2 个空值的集合。

在此处输入图像描述

我可以通过更改为来完成此工作,[JsonProperty(Order = int.MaxValue)]因此[JsonProperty(Order = int.MinValue)]首先对 Steps 进行序列化 - 但在我的场景中,我希望实际的 JSON 在平面AllContexts数组上具有其所有属性,并且 Steps 仅具有$ref如下所示的 s:

{
  "$id": "1",
  "AllContexts": [
    {
      "$id": "2",
      "Name": "1"
    },
    {
      "$id": "3",
      "Name": "2"
    }
  ],
  "Steps": [
    {
      "$id": "4",
      "Contexts": [
        {
          "$ref": "2"
        },
        {
          "$ref": "3"
        }
      ]
    }
  ]
}

这似乎是 JSON .NET 中的一个错误 - 有没有办法解决它?

标签: c#json.netjson.net

解决方案


推荐阅读