1
我有兩個文件,一個是json另一個是xml,我需要將兩者合併,我決定在concat/merge後在json中轉換xml。在JObject JSON.NET中更新JArray
{
"Level1": {
"Level2": [
{
"id": "Chart",
"Box": [
{
"id": "1",
"value": "10"
},
{
"id": "2",
"value": "20"
}
]
}
]
}
}
第二JSON:
{
"Level1": {
"Level2": [
{
"id": "NameApp",
"Box": [
{
"id": "2",
"value": "90"
},
{
"id": "3",
"value": "50"
}
]
}
]
}
}
OUTPUT:
{
"Level1": {
"Level2": [
{
"id": "Chart",
"Box": [
{
"id": "1",
"value": "10"
},
{
"id": "2",
"value": "20"
}, {
"id": "2",
"value": "90"
},
{
"id": "3",
"value": "50"
}
]
}
]
}
}
XML代碼:
XmlDocument doc = new XmlDocument();
doc.Load(pathXml);
doc.RemoveChild(doc.FirstChild);
string jsonTextXml = JsonConvert.SerializeXmlNode(doc);
JSON代碼:
using (StreamReader readerJson = new StreamReader(pathJson))
{
jsonTextJson = readerJson.ReadToEnd();
}
代碼合併:
JObject o1 = JObject.Parse(jsonTextJson);
JObject o2 = JObject.Parse(jsonTextXml);
JArray box1 = o1["Level1"]["Level2"]["Box"][0] as JArray;
JArray box2 = o2["Level1"]["Level2"]["Box"][0] as JArray;
box1 = new JArray(box1.Concat(box2));
o1["Level1"]["Level2"]["Box"][0].Replace(box1);
當我wannt得到BOX1,我有這樣的錯誤:對象引用未設置爲一個對象實例。
我用另一種方式來測試..
JArray box1 = o1["Level1"]["Level2"][0]["Box"] as JArray;
有什麼不對?
最後,這是我的解決方案解決方案:
public string joinJson(string jsonFinal, string jsonTemp)
{
JObject jsonMaster = JObject.Parse(jsonFinal);
JObject jsonForMerge = JObject.Parse(jsonTemp);
foreach (var element in jsonForMerge["Level1"]["Level2"])
{
string pathElement = element.Path;
string component = pathElement.Split(new char[] { '.' }).Last();
if (element.HasValues && !component.Equals("id"))
{
JArray contentTemp = jsonForMerge["Level1"]["Level2"][component] as JArray;
JArray contentFinal = jsonMaster["Level1"]["Level2"][0][component] as JArray;
contentFinal = new JArray(contentFinal.Concat(contentTemp));
jsonMaster["Level1"]["Level2"][0][component].Replace(contentFinal);
}
}
return jsonMaster.ToString();
}
一個問題如果我想在這個例子中得到2級,我該怎麼做?沒有以這種方式工作:JArray contentK = _jsonMaster [「Level1」] [「Level2」]作爲JArray; – 2015-02-09 15:33:07