【发布时间】:2015-10-01 15:16:12
【问题描述】:
我使用 JSON.net 将非常复杂的 XML 转换为 JSON 并将其反序列化为 C#。
string text = await blockBlob2.DownloadTextAsync();
XmlDocument doc = new XmlDocument();
doc.LoadXml(text);
string json = Newtonsoft.Json.JsonConvert.SerializeXmlNode(doc);
RootObject x = JsonConvert.DeserializeObject<RootObject>(json);
string output = JsonConvert.SerializeObject(x);
在从 XML 转换后,我遇到了 JSON 中出现“@”符号的问题。当我尝试对其进行序列化时,所有结构都有效,但字段的内容变为空。
根对象类:
/*
Licensed under the Apache License, Version 2.0
http://www.apache.org/licenses/LICENSE-2.0
*/
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace WorkerRole1
{
public class ItineraryOption
{
public string ODRef { get; set; }
public string From { get; set; }
public string To { get; set; }
public string Date { get; set; }
public string SeatsAvailable { get; set; }
public string TravelTime { get; set; }
public string ItineraryRef { get; set; }
public object FlightSegment { get; set; }
}
public class ItineraryOptions
{
public List<ItineraryOption> ItineraryOption { get; set; }
}
public class BookingGuidelines
{
public string RussianNamesSupported { get; set; }
}
public class DeepLink
{
public string DeviceType { get; set; }
//public string __invalid_name__#cdata-section { get; set; }
// public string __invalid_name__#text { get; set; }
}
public class DeepLinks
{
public List<DeepLink> DeepLink { get; set; }
}
public class ShopOption
{
public string OptionRef { get; set; }
public string Currency { get; set; }
public string Total { get; set; }
public string Airlines { get; set; }
public ItineraryOptions ItineraryOptions { get; set; }
public BookingGuidelines BookingGuidelines { get; set; }
public DeepLinks DeepLinks { get; set; }
}
public class ShopOptions
{
public List<ShopOption> ShopOption { get; set; }
}
public class SIGAirShopRS
{
public string CustomerID { get; set; }
public string SessionID { get; set; }
public string ProcessingTime { get; set; }
public string SIGVersion { get; set; }
public string SchemaVersion { get; set; }
public string BuildDate { get; set; }
public string Result { get; set; }
public ShopOptions ShopOptions { get; set; }
}
public class SIGResponse
{
public string xmlns { get; set; }
public SIGAirShopRS SIG_AirShopRS { get; set; }
}
public class RootObject
{
public SIGResponse SIG_Response { get; set; }
}
}
XML 示例: https://drive.google.com/file/d/0B3CEquA-V15lamN5UVRWeDdzR2M/view?usp=sharing
【问题讨论】:
-
添加您的 RootObject 类和示例数据
-
为什么先转 JSON 然后转 C# 对象而不是直接转 XML 对象?
-
你遇到的问题是“@”号引起的吗?如果您不确定是否应该仔细检查,然后可能会“转义”该角色。
-
需要转换以备将来使用。添加类
-
找到了解决方法,不确定是不是最好的方法:XmlDocument doc = new json=json.Replace("@", "");
标签: c# json xml serialization json.net