测试用例
public class Child
{
public int a = 1;
}
public class Parent
{
private List<Child> _Children = new List<Child>() { new Child() };
public List<Child> Children
{
get
{
return _Children;
}
set
{
_Children = value;
}
}
}
class TestClass
{
public static void Test()
{
var parent = new Parent
{
Children = new List<Child>{ new Child() }
};
var serializedParent = JsonConvert.SerializeObject(parent);
var deserializedParent = JsonConvert.DeserializeObject<Parent>(serializedParent);
var reserializedParent = JsonConvert.SerializeObject(deserializedParent);
Console.WriteLine(serializedParent); // {"Children":[{"a":1}]}
Console.WriteLine(reserializedParent); // {"Children":[{"a":1},{"a":1}]}
}
}
解决方案
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ObjectCreationHandling = ObjectCreationHandling.Replace; // 用替换代替默认的处理
JsonConvert.DeserializeObject<Parent>(serializedParent, settings);
来源
来源