【问题标题】:How to desirialize the http web response如何反序列化 http web 响应
【发布时间】:2014-07-10 06:04:00
【问题描述】:

我在 asp.net 应用程序中使用 google API 来获取两个区域之间的距离。

结果是休闲

{
   "destination_addresses" : [ "Dhantoli, Nagpur, Maharashtra, India" ],
   "origin_addresses" : [ "Khamla, Nagpur, Maharashtra, India" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "4.2 km",
                  "value" : 4214
               },
               "duration" : {
                  "text" : "8 mins",
                  "value" : 467
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

我已经将它收集在字符串中并尝试获取距离文本(这是我需要的)

为此我已经尝试了它不起作用的休闲代码

DistanceMatrix data = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<DistanceMatrix>(dataString);

dataString 是 API 的结果

public class DistanceMatrix {
    public string destination_addresses { get; set; }
    public string origin_addresses { get; set; }
    public Element rows { get; set; }
    public string status { get; set; }
}
public class Element {
    public Data distance { get; set; }
    public Data duration { get; set; }
    public string status { get; set; }
}
public class Data {
   public string text { get; set; }
   public string value { get; set; }
}

请帮我从 API 结果中获取距离文本。

【问题讨论】:

    标签: json serialization deserialization httpwebresponse javascriptserializer


    【解决方案1】:

    不要使用json方法,而是使用google distance matrix api的XML api。

    返回 xml 响应以字符串形式收集并将其解析为休闲。

    XmlDocument xmldoc = new XmlDocument();
    xmldoc.LoadXml(dataString);
    if (xmldoc.GetElementsByTagName("status")[0].ChildNodes[0].InnerText == "OK")
    {
         XmlNodeList distance = xmldoc.GetElementsByTagName("distance");
    }
    

    【讨论】:

    • 这并没有回答关于如何使用 JSON 来完成的问题(这是完全可能的)。也许您应该编辑问题,使其与 XML 有关?
    猜你喜欢
    • 2019-10-28
    • 1970-01-01
    • 2014-08-08
    • 1970-01-01
    • 2011-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多