C# 仅使用本机.NET方法将XML字符串转换为JSON
我正在尝试将php函数重写为C#。php函数将XML字符串转换为JSON 起初,我想到了这个:C# 仅使用本机.NET方法将XML字符串转换为JSON,c#,asp.net,json,json.net,C#,Asp.net,Json,Json.net,我正在尝试将php函数重写为C#。php函数将XML字符串转换为JSON 起初,我想到了这个: string[] zips = { "27249","27215"}; // Request.Form.Get("zip").ToArray(); List<string> listings = new List<string>(); var webClient = new WebClient(); for (int i =
string[] zips = { "27249","27215"}; // Request.Form.Get("zip").ToArray();
List<string> listings = new List<string>();
var webClient = new WebClient();
for (int i = 0; i != zips.Length; i++)
{
string returnXml = webClient.DownloadString("http://gateway.moviefone.com/movies/pox/closesttheaters.xml?zip=" + zips[i]);
var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(returnXml);
listings.Add(json);
Response.Write(json);
}
string returnXml = webClient.DownloadString("http://gateway.moviefone.com/movies/pox/closesttheaters.xml?zip=" + zips[i]);
var xmlDoc = new System.Xml.XmlDocument();
xmlDoc.LoadXml(returnXml);
var json = JsonConvert.SerializeXmlNode(xmlDoc);
listings.Add(json);
让我烦恼的是,将Xml字符串转换为XmlDocument只是为了将其转换回JSON字符串似乎没有必要。我希望JSON字符串稍后在jQuery函数中使用
如何使第一个版本仅使用内在的.NET方法工作
谢谢。我不能告诉您是否有一个预制作的工具可以满足您的需求,但是如果您希望从这个转换中获得每一点性能,您可以使用JsonReader读取JSON流,然后使用XmlWriter将其输出到XML流
话虽如此,如果您得到的JSON来自互联网,您不太可能显著提高性能。但是,您可能会引入bug。我建议您不要这样做如果您坚持要将Xml转换为JSON,那么为什么您反对创建Xml对象?我并不反对,我最想知道的是为什么首先需要创建Xml对象。如果传入的字符串是从XML转换而来的,为什么还要费心进行另一次转换以将其转换回JSON字符串呢?这是因为XmlDoc已经验证并将字符串“转换”为XML。如果要调用XML参数方法,为什么不编写自己的方法呢?