Search code examples
jsonserializationdeserializationhttpwebresponsejavascriptserializer

How to desirialize the http web response


I have used the google API for the getting distance between two area in my asp.net application.

which give the result as fallow

{
   "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"
}

I have collect it in string and try to get the distance text(which is i needed)

for that i have tried the fallowing code it does not working

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

dataString is the result from 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; }
}

Please help me to get the distance text from the API result.


Solution

  • Instead of using json method use the XML api of google distance matrix api.

    Which return the xml response collect it in string and parse it as fallow.

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