Json反序列化,创建重复的对象

时间:2013-07-22 11:54:00

标签: c# .net json deserialization

更容易展示问题的模拟,而不是先尝试解释它。

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表现得如此不重复?

希望有意义

史蒂夫

1 个答案:

答案 0 :(得分:2)

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

    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