从 Windows phone 7 中的 XML 读取 JSON 并绑定到 ListBox



我想从XML响应中获取JSON数据。实际上 Web 服务返回的响应如下:

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
[
    {
        "id": 1,
        "name": "paresh",
    },
    {
        "id": 2,
        "name": "jacob",
    },
    {
        "id": 3,
        "name": "color",
    },
    {
        "id": 4,
        "name": "Adil color",
    }
]</string>

我已经参考了一些文章。如果响应只是XML,那么我可以实现如下:

   MyListBox.ItemsSource = from tweet in xmlTweets.Descendants("student")
                                          select new StudentItem
                                          {
                                              ID = tweet.Element("id").Value,
                                              Name = tweet.Element("name").Value,
                                          };

但是在这里,我的问题是获取内部的JSON,并显示在ListBox中?

您可以通过使用 ScriptMethod 属性修饰 Web 方法来定义 Web 方法响应格式。代码就是这样。

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

获得 json 格式字符串的代码后,您可以在 json 中解析它。

如果您有任何疑问,请告诉我。

更新:

因此,您必须从子字符串方法中手动删除<string>标签。这是您的代码。

string Header = "<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">";
        string str = "<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">[{"id": 1,"name": "paresh"}]</string>";
        string TempStr = str.Remove(0, Header.Length);
        string FinalStr = TempStr.Substring(0, TempStr.Length - 9);

FinalStr 是你的 json 字符串。

你可能想使用用 Scala 编写的 Twitter finagle 将 xml 转换为 json,如下所示:

 val xmlResponse = <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
     [
         {
            "id": 1,
            "name": "paresh",
          },
          {
             "id": 2,
             "name": "jacob",
           },
           {
              "id": 3,
              "name": "color",
           },
          {
                "id": 4,
                "name": "james bond",
           }
     ]</string>
  val properties = (xmlResponse \ "string")    //parse the xml
  val responseContent = xmlResponse.toSeq.toJson.toString()

您可以通过以下方式查看:

  println(responseContent)

在你选择finagle之前,尝试一个scala中的简单例子,然后你可能想探索finagle库。它在操作来自众多服务器(电子邮件、asp.net 的不同类型的响应时很有用。SQL,短信仅举几例)。

我会像您发布的那样使用初始 XML,然后使用 JSON.Net 等库来操作 XML,提取 JSON 并将其存储在对象中,然后再将其绑定到您的 ListBox。

以下是关于 JSON.Net 的几个要点(摘自网站)

  • 灵活的 JSON 序列化程序,用于在 .NET 对象和 JSON 之间进行转换
  • LINQ to JSON,用于手动读取和写入 JSON
  • 高性能,比 .NET 的内置 JSON 序列化程序
  • 写入缩进,易于读取 JSON
  • 将 JSON 与 XML 相互转换
  • 支持 .NET 2、.NET
  • 3.5、.NET 4、Silverlight 和 Windows Phone

最新更新