【发布时间】:2014-06-25 23:45:09
【问题描述】:
我正在尝试将 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 = 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);
}
但输出包含编码字符,这不是我想要的。
然后,使用 JSON.NET,我将循环体替换为:
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 方法工作?
谢谢。
【问题讨论】:
-
如果你坚持将 Xml 转换为 JSON,那你为什么反对创建 Xml 对象呢?
-
我并不反对它,我主要是好奇为什么它首先是必要的。如果传入的字符串是从 XML 转换而来的,为什么还要再进行一次转换才能将其转换回 JSON 字符串?
-
这是因为 XmlDoc 已验证字符串并将其“转换”为 Xml。
-
你在调用一个Xml参数方法,为什么不自己写呢?