Google Geocoding Json Parsing Issue in C#

前端 未结 2 1754
孤街浪徒
孤街浪徒 2020-12-18 14:37

I have my code working fine, but I can\'t seem to be able to get to the deeper parts of the tree. I\'m trying to pull the longitude and the latitude. The code below pulls \'

相关标签:
2条回答
  • 2020-12-18 15:10

    Here are the steps to get what you want:

    1. Post your JSON in http://json2csharp.com/. Take the resulting classes and merge duplicates, and you get:

      public class AddressComponent
      {
          public string long_name { get; set; }
          public string short_name { get; set; }
          public List<string> types { get; set; }
      }
      
      public class Bounds
      {
          public Location northeast { get; set; }
          public Location southwest { get; set; }
      }
      
      public class Location
      {
          public double lat { get; set; }
          public double lng { get; set; }
      }
      
      public class Geometry
      {
          public Bounds bounds { get; set; }
          public Location location { get; set; }
          public string location_type { get; set; }
          public Bounds viewport { get; set; }
      }
      
      public class Result
      {
          public List<AddressComponent> address_components { get; set; }
          public string formatted_address { get; set; }
          public Geometry geometry { get; set; }
          public bool partial_match { get; set; }
          public List<string> types { get; set; }
      }
      
      public class RootObject
      {
          public List<Result> results { get; set; }
          public string status { get; set; }
      }
      

      (You could also use Paste JSON as Classes or https://jsonutils.com/ to generate your initial type definitions.)

    2. Deserialize your JSON with Json.NET like so:

          var root = JsonConvert.DeserializeObject<RootObject>(result);
      
    3. There are multiple results returned for your query, so you need to loop through the locations returned like so:

          foreach (var singleResult in root.results)
          {
              var location = singleResult.geometry.location;
              var latitude = location.lat;
              var longitude = location.lng;
              // Do whatever you want with them.
          }
      
    0 讨论(0)
  • 2020-12-18 15:22

    The syntax for 'geometry' -> 'location' -> 'lat' and 'lng' is:

    JObject data = JObject.Parse(result);
    
    string lat = (string)data["results"][0]["geometry"]["location"]["lat"];
    string lng = (string)data["results"][0]["geometry"]["location"]["lng"];
    
    0 讨论(0)
提交回复
热议问题