4

展示问题的模型比试图先解释它更容易。

internal class Program
{
    private static void Main(string[] args)
    {
        Class1 class1 = new Class1() { Name = "Scott" };
        Class2 class2 = new Class2() { Name = "Steve", Objects = new List<Class1>() { class1 } };
        Class2 class22 = new Class2() { Name = "Atanas", Objects = new List<Class1>() { class1 } };

        List<Class2> list = new List<Class2>() { class2, class22 };
        string jSonString = JsonConvert.SerializeObject(list,Formatting.Indented,
                                    new JsonSerializerSettings()
                                        {
                                            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                                        });


        List<Class2> result = (List<Class2>) JsonConvert.DeserializeObject(jSonString, typeof(List<Class2>));

        if (result[0].Objects[0] == result[1].Objects[0])
        {
            Console.WriteLine("Correct, its the same object");
        }
        else
        {
            Console.WriteLine("Bah!, its a new object");
        }
    }
}

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

public class Class2
{
    public Class2()
    {
        Objects = new List<Class1>();
    }

    public List<Class1> Objects { get; set; }
    public string Name { get; set; }
}

问题是当字符串被反序列化时,“共享对象”现在被复制了。在被序列化之前,同一个对象(通过引用)位于两个单独的列表中。在对两个列表进行反序列化后,它们都包含单独的对象。

是否可以让 json 表现得不重复?

希望这是有道理的

史蒂夫

4

1 回答 1

3

是的,如果您按如下方式设置序列化程序:

    JsonSerializerSettings settings = new JsonSerializerSettings
    {
        PreserveReferencesHandling = PreserveReferencesHandling.All
    };

Json 字符串将是:

{
  "$id": "1",
  "$values": [
    {
      "$id": "2",
      "Objects": {
        "$id": "3",
        "$values": [
          {
            "$id": "4",
            "Name": "Scott"
          }
        ]
      },
      "Name": "Steve"
    },
    {
      "$id": "5",
      "Objects": {
        "$id": "6",
        "$values": [
          {
            "$ref": "4"
          }
        ]
      },
      "Name": "Atanas"
    }
  ]
}

您将在控制台中看到:

正确,它是同一个对象

请参阅http://james.newtonking.com/projects/json/help/index.html?topic=html/T_Newtonsoft_Json_PreserveReferencesHandling.htm

于 2013-07-22T14:03:13.640 回答