我正在使用JsonConvert将Json对象反序列化为XML,但由于Json对于同一级别的元素具有不同的结构,因此我在生成的XML中获得了重复的节点。
我的Json看起来像这样:
{
"shipments": [
{
"id": "A000001",
"name": "20141208 140652",
"type": "OUTLET",
"date": "2014-12-08 14:06:52",
"status": "SENT",
"received_at": null,
"created_at": "2014-12-08 14:06:52",
"updated_at": null,
"outlet_id": "SH000064"
},
{
"id": "A000002",
"name": "20141204 122650",
"type": "SUPPLIER",
"date": "2014-12-04 12:26:50",
"outlet_id": "SH000064",
"supplier_id": null,
"status": "RECEIVED",
"received_at": "2014-12-04 12:28:43",
"created_at": "2014-12-04 12:26:50",
"updated_at": "2014-12-04 12:28:43"
}
]
}
转换后,XML看起来像这样:
<root>
<shipments>
<id>A000001</id>
<name>20141208 140652</name>
<type>OUTLET</type>
<date>2014-12-08 14:06:52</date>
<status>SENT</status>
<received_at />
<created_at>2014-12-08 14:06:52</created_at>
<updated_at />
<outlet_id>SH000064</outlet_id>
</shipments>
<shipments>
<id>A000002</id>
<name>20141204 122650</name>
<type>SUPPLIER</type>
<date>2014-12-04 12:26:50</date>
<outlet_id>SH000064</outlet_id>
<supplier_id />
<status>RECEIVED</status>
<received_at>2014-12-04 12:28:43</received_at>
<created_at>2014-12-04 12:26:50</created_at>
<updated_at>2014-12-04 12:28:43</updated_at>
<outlet_id>SH000064</outlet_id>
</shipments>
</root>
我用来转换Json的代码是:
var document = JsonConvert.DeserializeXmlNode(json, "root");
var xml = document.OuterXml;
问题是第二个货件元素中的outlet_id节点重复。输入Json通过验证,所以我认为这是一个常见问题。有办法吗?
更新:进一步调试显示在提交和处理HttpWebRequest期间引入了额外节点。如果我通过Postman应用程序调用REST服务,我会得到上面给出的Json(为简单起见,使用截断)。如果我通过我的C#代码调用该服务,我会改为:
{
"shipments": [
{
"id": "A000001",
"name": "20141208 140652",
"type": "OUTLET",
"date": "2014-12-08 14:06:52",
"status": "SENT",
"received_at": null,
"created_at": "2014-12-08 14:06:52",
"updated_at": null,
"outlet_id": "SH000064"
},
{
"id": "A000002",
"name": "20141204 122650",
"type": "SUPPLIER",
"date": "2014-12-04 12:26:50",
"outlet_id": "SH000064",
"supplier_id": null,
"status": "RECEIVED",
"received_at": "2014-12-04 12:28:43",
"created_at": "2014-12-04 12:26:50",
"updated_at": "2014-12-04 12:28:43",
"outlet_id": "SH000064"
}
]
}
我用来提交请求和处理响应的代码是:
HttpWebRequest request = WebRequest.Create(Uri.EscapeUriString(url)) as HttpWebRequest;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
var responseStream = reader.ReadToEnd();
reader.Close();
此阶段的断点显示附加节点已添加到通过流式传输响应返回的Json。
执行相同的调用,其中返回的数据都是相同的类型,因此结构,不会创建重复的节点,因此,这可能是由一个&#34;货物&#34;元素与同行的结构不同。