使用 Windows Phone 将 JSON 解析为 XML
我有这段代码,但无法使其全部正常工作。
我正在尝试将 json 字符串转换为 xml。这样我在解析数据时可以获得项目列表。有没有更好的方法将json解析为xml。
如果是这样,最好的方法是什么,如果可能的话,你能给我一个可行的例子吗?
代码中的 URL 不是我正在使用的 URL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Bson;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Linq;
using System.Xml.Linq.XDocument;
using System.IO;
namespace WindowsPhonePanoramaApplication3
{
public partial class Page2 : PhoneApplicationPage
{
public Page2()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e1)
{
/* because the origional JSON string has multiple root's this needs to be added */
string json = "{BFBC2_GlobalStats:";
json += DownlodUrl("http://api.bfbcs.com/api/xbox360?globalstats");
json += "}";
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeObject(json);
textBox1.Text = GetXmlString(doc);
}
private string GetXmlString()
{
throw new NotImplementedException();
}
private string DownlodUrl(string url)
{
string result = null;
try
{
WebClient client = new WebClient();
result = client.DownloadString(url);
}
catch (Exception ex)
{
// handle error
result = ex.Message;
}
return result;
}
private string GetXmlString(XmlDocument xmlDoc)
{
sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
xw.Formatting = System.Xml.Formatting.Indented;
xmlDoc.WriteTo(xw);
return sw.ToString();
}
}
}
该 URL 输出以下代码:
{"StopName":"Race Hill",
"stopId":7553,
"NaptanCode":"bridwja",
"LongName":"Race Hill",
"OperatorsCode1":" 5",
"OperatorsCode2":" ",
"OperatorsCode3":" ",
"OperatorsCode4":"bridwja",
"Departures":[
{
"ServiceName":"",
"Destination":"",
"DepartureTimeAsString":"",
"DepartureTime":"30/01/2012 00:00:00",
"Notes":""}`
感谢您的回复。那么我是否应该将数据保留为 json,然后通过它查看数据???
这是一种显示 json 字符串数据的方法吗?
public void Load()
{
// form the URI
UriBuilder uri = new UriBuilder("http://mysite.com/events.json");
WebClient proxy = new WebClient();
proxy.OpenReadCompleted += new OpenReadCompletedEventHandler(OnReadCompleted);
proxy.OpenReadAsync(uri.Uri);
}
void OnReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
var serializer = new DataContractJsonSerializer(typeof(EventList));
var events = (EventList)serializer.ReadObject(e.Result);
foreach (var ev in events)
{
Items.Add(ev);
}
}
}
public ObservableCollection<EventDetails> Items { get; private set; }
编辑: 现在将 url 保留为 json,并使用 json 方式使其正常工作。
I have this code, but can't get it all working.
I am trying to get a json string into xml. So that I can get a list of items when i parse the data. Is there a better way to parse json into xml.
If so what's the best way to do it, and if possible could you give me a working example?
The URL that is in the code is not the URL that i am using
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Bson;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Linq;
using System.Xml.Linq.XDocument;
using System.IO;
namespace WindowsPhonePanoramaApplication3
{
public partial class Page2 : PhoneApplicationPage
{
public Page2()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e1)
{
/* because the origional JSON string has multiple root's this needs to be added */
string json = "{BFBC2_GlobalStats:";
json += DownlodUrl("http://api.bfbcs.com/api/xbox360?globalstats");
json += "}";
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeObject(json);
textBox1.Text = GetXmlString(doc);
}
private string GetXmlString()
{
throw new NotImplementedException();
}
private string DownlodUrl(string url)
{
string result = null;
try
{
WebClient client = new WebClient();
result = client.DownloadString(url);
}
catch (Exception ex)
{
// handle error
result = ex.Message;
}
return result;
}
private string GetXmlString(XmlDocument xmlDoc)
{
sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
xw.Formatting = System.Xml.Formatting.Indented;
xmlDoc.WriteTo(xw);
return sw.ToString();
}
}
}
The URL outputs the following code:
{"StopName":"Race Hill",
"stopId":7553,
"NaptanCode":"bridwja",
"LongName":"Race Hill",
"OperatorsCode1":" 5",
"OperatorsCode2":" ",
"OperatorsCode3":" ",
"OperatorsCode4":"bridwja",
"Departures":[
{
"ServiceName":"",
"Destination":"",
"DepartureTimeAsString":"",
"DepartureTime":"30/01/2012 00:00:00",
"Notes":""}`
Thanks for your responses. So Should i just leave the data a json and then view the data via that???
Is this a way to show the data from a json string.
public void Load()
{
// form the URI
UriBuilder uri = new UriBuilder("http://mysite.com/events.json");
WebClient proxy = new WebClient();
proxy.OpenReadCompleted += new OpenReadCompletedEventHandler(OnReadCompleted);
proxy.OpenReadAsync(uri.Uri);
}
void OnReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
var serializer = new DataContractJsonSerializer(typeof(EventList));
var events = (EventList)serializer.ReadObject(e.Result);
foreach (var ev in events)
{
Items.Add(ev);
}
}
}
public ObservableCollection<EventDetails> Items { get; private set; }
Edit:
Have now kept the url as json and have now got it working by using the json way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道为什么要把它转换成 XML,为什么不直接解析成对象呢?
使用类似 http://json2csharp.com/ 的内容来生成您的类。然后使用 DataContractJsonDeserializer 将 Json 读入对象中。有关如何进行该操作的示例,请参阅这篇 MSDN 文章。
再次编辑:啊,我看到你已经在使用 Newtonsoft.JSON - 这是内置反序列化的一个很好的替代方案。您可以使用它来反序列化为一组对象。
I'm not sure why you want to convert it into XML, why not just parse directly into objects?
Use something like http://json2csharp.com/ to generate your classes. Then use the DataContractJsonDeserializer to read the Json into the objects. For an example of how to go about that bit, please see this MSDN article.
Edt again : Ah, I see you are already using Newtonsoft.JSON - that is a good alternative to the built-in deserialisation. You can use that to deserialise to a set of objects.
ZombieSheep 正确地询问了为什么要从 JSON 转换为 XML。您应该将响应目录转换为业务对象。从那里,您可以调用一个方法将其序列化为 XML,但我强烈建议您在获取列表之前重新考虑一下关于转换为 XML 的想法。
ZombieSheep is correct in asking why you want to convert from JSON to XML. You should convert the response directory to a business object. From there, you could invoke a method to serialize it to XML, but I highly recommend you rethink your idea about converting to XML before obtaining a list.