想象一下我有一个带有两个不同对象的类:
Object A contains string A1 and string A2
Object B contains string B1 and string B2
如果我要序列化该类,则json看起来像这样
{
"ObjectA" : {
"A1" : "foo",
"A2" : "bar"
},
"ObjectB": {
"B1" : "foo",
"B2" : "bar"
}
}
但是,该类结构仅用于帮助填充类,并不代表我所需的实际结构。它应该看起来像这样:
{
"A1": "foo",
"A2": "bar",
"B1": "foo",
"B2": "bar"
}
是否可以使用Newtonsoft来实现此目的而又不将A1,A2,B1和B2映射到另一个类?
答案 0 :(得分:1)
您可以使用Merge
https://www.newtonsoft.com/json/help/html/MergeJson.htm
一种解决方法是从JObject中提取ObjectA
和ObjectB
,然后使用Merge获得所需的输出
JObject obj = JObject.Parse(@"{
'ObjectA' : {
'A1' : 'foo',
'A2' : 'bar'
},
'ObjectB': {
'B1' : 'foo',
'B2' : 'bar'
}
} ");
JObject objectA = obj.SelectToken("ObjectA") as JObject;
JObject objectB = obj.SelectToken("ObjectB") as JObject;
objectA.Merge(objectB, new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Union });
string json = objectA.ToString();