假设我有以下简单代码:
using System;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace TestSomeCodeSnippets.JsonTest
{
public class JsonTest2
{
public JsonTest2(string field3, int field4)
{
Field3 = field3;
Field4 = field4;
}
public string Field3 { get; set; }
public int Field4 { get; set; }
public JsonTest Parent { get; set; }
}
public class JsonTest
{
public JsonTest(string field1, int field2, List<JsonTest2> children)
{
Field1 = field1;
Field2 = field2;
Children = children;
foreach (var jsonTest2 in children)
{
jsonTest2.Parent = this;
}
}
public string Field1 { get; set; }
public int Field2 { get; set; }
public List<JsonTest2> Children { get; set; }
public static void Main()
{
var ch1 = new JsonTest2("1", 1);
var ch2 = new JsonTest2("2", 2);
var parent = new JsonTest("parent", 0, new List<JsonTest2> {ch1, ch2});
var z1 = JsonConvert.SerializeObject(parent, new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
});
var z2 = JsonConvert.DeserializeObject<IDictionary>(z1, new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
});
Console.ReadLine();
}
}
}
首先将对象序列化为json然后反序列化为IDictionary的对象之间存在父子关系。我需要在反序列化到IDictionary之后,对象$ id也作为键值属性出现。这是必要的,因为我使用第三方库,首先将数据反序列化为IDictionary,然后提供反序列化到我的对象的可能性(简单地说 - 它将我的对象包装到IDictionary中)。但是在经过所有这些操作之后,父对象的$ id就会丢失,所以在它的内容中,对它的反映就是空的。
有可能吗?
提前致谢。
更新 序列化的json:
{
"$id": "1",
"Field1": "parent",
"Field2": 0,
"Children": [
{
"$id": "2",
"Field3": "1",
"Field4": 1,
"Parent": {
"$ref": "1"
}
},
{
"$id": "3",
"Field3": "2",
"Field4": 2,
"Parent": {
"$ref": "1"
}
}]
}
反序列化的json(IDicitionary)看起来像:
base {Newtonsoft.Json.Linq.JContainer} =
[
{
"$id": "2",
"Field3": "1",
"Field4": 1,
"Parent": {
"$ref": "1"
}
},
{
"$id": "3",
"Field3": "2",
"Field4": 2,
"Parent": {
"$ref": "1"
}
}
]
请注意,对于反序列化的对象initial&#34; $ id&#34;:&#34; 1&#34;缺少......