gpt4 book ai didi

c# - Json反序列化,创建重复对象

转载 作者:行者123 更新时间:2023-11-30 17:04:12 24 4
gpt4 key购买 nike

展示问题模型比先尝试解释问题更容易。

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 的行为不重复?

希望这是有道理的

史蒂夫

最佳答案

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

    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"
}
]
}

你会在控制台看到:

Correct, its the same object

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

关于c# - Json反序列化,创建重复对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17786924/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com