【问题标题】:C# asp.net MVC wiring up one json output from Google MAPS AutoComplete API to a different json outputC# asp.net MVC 将来自 Google MAPS AutoComplete API 的一个 json 输出连接到另一个 json 输出
【发布时间】:2015-08-23 17:07:05
【问题描述】:

我的 ASP.NET MVC 项目中有一个类调用 Google MAPS 自动完成 API

public ActionResult Autocomplete(string term)
    {
        var url = String.Format(" https://maps.googleapis.com/maps/api/place/autocomplete/json?input=" + term + "&types=address&location=53.4333,-7.9500&radius=250&key=MYKEY");
        var jsonautocomplete = new System.Net.WebClient().DownloadString(url);

        JavaScriptSerializer jss = new JavaScriptSerializer();
        Rootobject autocomplete = JsonConvert.DeserializeObject<Rootobject>(jsonautocomplete);
        string suggestions = (autocomplete.predictions[5].description[0].value);
        return Json(suggestions, JsonRequestBehavior.AllowGet);
    }

这是为了创建对 Google MAPS API 的调用,该 API 根据值动态创建 API 的 URL,该值又作为术语传递给函数。

我在同一个控制器中也有支持类来反序列化(不确定这是正确的术语)返回的 JSON。

public class Rootobject
{
    public Prediction[] predictions { get; set; }
    public string status { get; set; }
}

public class Prediction
{
    public string description { get; set; }
    public string id { get; set; }
    public Matched_Substrings[] matched_substrings { get; set; }
    public string place_id { get; set; }
    public string reference { get; set; }
    public Term[] terms { get; set; }
    public string[] types { get; set; }
}

public class Matched_Substrings
{
    public int length { get; set; }
    public int offset { get; set; }
}

public class Term
{
    public int offset { get; set; }
    public string value { get; set; }
}

我可以看到这正确返回了包含地址建议的 JSON 格式数据,但我在正确反序列化它时遇到了问题

{
   "predictions" : [
      {
         "description" : "92 Howth Road, Clontarf, Ireland",
         "id" : "c949817fec719bf89a8f03aa5e4e24bb26c3c2c2",
         "matched_substrings" : [
            {
               "length" : 8,
               "offset" : 0
            }
         ],
         "place_id" : "EiA5MiBIb3d0aCBSb2FkLCBDbG9udGFyZiwgSXJlbGFuZA",
         "reference" : "ClROAAAAPPyMTROIaAQ52qM2ixB_TY7ZHczbKDWLzIRQHXP0bfo3-qRjDKyuNgg9xbzUweWRkEleIbRh9P-Pp9dsyrgPXI9cHNlzi6Em-mQzLiFyh0ESEA21MGZZ9E_kgFc9idXn73gaFIuJF8FsllcDIoi4XFc7iLsp814l",
         "terms" : [
            {
               "offset" : 0,
               "value" : "92 Howth Road"
            },
            {
               "offset" : 15,
               "value" : "Clontarf"
            },
            {
               "offset" : 25,
               "value" : "Ireland"
            }
         ],
         "types" : [ "route", "geocode" ]
      },
      {
         "description" : "92 Howth Road, Dublin, Ireland",
         "id" : "58992f3ede4055683f2d67510aae48913e7b196c",
         "matched_substrings" : [
            {
               "length" : 8,
               "offset" : 0
            }
         ],
         "place_id" : "Eh45MiBIb3d0aCBSb2FkLCBEdWJsaW4sIElyZWxhbmQ",
         "reference" : "ClRMAAAA5neJBhWV_AstgsVtw-pahbLn406FbDBgehGuQbj5totChvsPNnPXkVwmqYnzZ38FOliK-egwTXaa195I92MYrkc6cOHHhRzUnZTTrzTx3CUSEJq0FGcZDiudfzUtWvRDHC4aFOqddOIfGFfrSu3kcCCpOIiCSm-m",
         "terms" : [
            {
               "offset" : 0,
               "value" : "92 Howth Road"
            },
            {
               "offset" : 15,
               "value" : "Dublin"
            },
            {
               "offset" : 23,
               "value" : "Ireland"
            }
         ],
         "types" : [ "route", "geocode" ]
      },
      {
         "description" : "92 Howth View Park, Dublin, Ireland",
         "id" : "6947a633c77f6fb087893ce39a7a22c862d3d9cb",
         "matched_substrings" : [
            {
               "length" : 8,
               "offset" : 0
            }
         ],
         "place_id" : "EiM5MiBIb3d0aCBWaWV3IFBhcmssIER1YmxpbiwgSXJlbGFuZA",
         "reference" : "CmRRAAAAcJV1nTt6EfZ2hhapaCETKtHE08S7WSqH6kwD57jiUtrRrVMvktjzL-Bftb5RHU1g4Sbe4bOPZUUzn5qMTI-GJWNNrpEz5iNNPRihRZMq5Q-TLFSCGhETXog3vhRWguIhEhAqvFrZnOTos2fsljbScA0EGhTEcsUy1-uXeRJoClm7jO2QoNj3ow",
         "terms" : [
            {
               "offset" : 0,
               "value" : "92 Howth View Park"
            },
            {
               "offset" : 20,
               "value" : "Dublin"
            },
            {
               "offset" : 28,
               "value" : "Ireland"
            }
         ],
         "types" : [ "route", "geocode" ]
      },
      {
         "description" : "92 Howth Track, Ashtown, Dublin, Ireland",
         "id" : "abb6fb12e2455de2a931729152b626c0f213ac82",
         "matched_substrings" : [
            {
               "length" : 8,
               "offset" : 0
            }
         ],
         "place_id" : "Eig5MiBIb3d0aCBUcmFjaywgQXNodG93biwgRHVibGluLCBJcmVsYW5k",
         "reference" : "CmRWAAAADGi1rI3efQ6CqZ9zu9qc9gstGf7kZiN973ZyqkeZNnZnyilV2A-dvo7Y8tPad8DNR_ovNeuXGmZDNhPZTjbv0G4D2Jrmdk5qtvBRQDg0EUMtcUNuOzwp_8coqoFI4zLGEhBSurI0GFQlC5X25rJ4MWH2GhRGJN63O_Qx_uVz9tajiILekzPEug",
         "terms" : [
            {
               "offset" : 0,
               "value" : "92 Howth Track"
            },
            {
               "offset" : 16,
               "value" : "Ashtown"
            },
            {
               "offset" : 25,
               "value" : "Dublin"
            },
            {
               "offset" : 33,
               "value" : "Ireland"
            }
         ],
         "types" : [ "route", "geocode" ]
      },
      {
         "description" : "92 Howth Terrace, Dublin, Ireland",
         "id" : "bf78cde30e173f6e2fbc62fac3bd4a1c31829303",
         "matched_substrings" : [
            {
               "length" : 8,
               "offset" : 0
            }
         ],
         "place_id" : "EiE5MiBIb3d0aCBUZXJyYWNlLCBEdWJsaW4sIElyZWxhbmQ",
         "reference" : "ClRPAAAA_gOsPjZCyAcES4P3ohJQTtJp4bGzP-gwZHioxoBbSbQjqRG2Z0-v89vBsJ6pSVBW_GVMvIFU7tIS_4TaDp2qr6Ah0XwmhY6wBaeO3Aq-Jt4SEJfAyiwx6XmaJGQUI6iHbTYaFBnIlHERvz37KRM7bp211RgWjC7J",
         "terms" : [
            {
               "offset" : 0,
               "value" : "92 Howth Terrace"
            },
            {
               "offset" : 18,
               "value" : "Dublin"
            },
            {
               "offset" : 26,
               "value" : "Ireland"
            }
         ],
         "types" : [ "route", "geocode" ]
      }
   ],
   "status" : "OK"
}

但是

建议字符串为空(它应该包含从 Google MAPS 解析 JSON 并获取描述属性返回的建议 - API 返回最佳 5 个匹配项)并且 Visual Studio 引发超出范围异常。

我很确定错误在于这行代码没有正确反序列化 JSON。

 string suggestions = (autocomplete.predictions[5].description[0].value);

我正在尝试将这些值传递到与此控制器相关的实体的索引视图上的 JQUERY 函数中,如下所示:

<form method="get" action="@Url.Action("Index")" 
      data-otf-ajax="true" data-otf-target="#restaurantList">

    <input type="search" name="searchTerm" data-otf-autocomplete="@Url.Action("Autocomplete")" />
    <input type="submit" value="Search By Name" />
</form>

返回的 JSON 需要包含类似于以下格式的值

[0] {label ="92 Howth Road, Clontarf, Ireland"
[1] {label ="92 Howth Road, Dublin, Ireland"}
[2] {label ="92 Howth View Park, Dublin, Ireland"}

抱歉,如果上面的 JSON 格式不准确,我只是想显示从 Google MAPS API 返回的较长的 JSON 属性列表中的哪一个我有兴趣自动填充到表单中。

正如您将在上面看到的,这些是最初返回的 JSON 中的“描述”属性

我将非常感谢有关如何正确更新此行以获取正确值的建议:

string suggestions = (autocomplete.predictions[5].description[0].value);

谢谢

【问题讨论】:

    标签: c# jquery json asp.net-mvc google-maps


    【解决方案1】:

    尝试在您的班级中使用列表而不是数组http://json2csharp.com/

    PS,VS paste special as classes 做同样的事情。(反序列化是正确的)

    public class MatchedSubstring
    {
      public int length { get; set; }
      public int offset { get; set; }
    }
    
    public class Term
    {
    public int offset { get; set; }
    public string value { get; set; }
    }
    
    public class Prediction
    {
    public string description { get; set; }
    public string id { get; set; }
    public List<MatchedSubstring> matched_substrings { get; set; }
    public string place_id { get; set; }
    public string reference { get; set; }
    public List<Term> terms { get; set; }
    public List<string> types { get; set; }
    }
    
    public class RootObject
    {
    public List<Prediction> predictions { get; set; }
    public string status { get; set; }
    }
    

    【讨论】:

    • 您好,谢谢您的回复。我已经尝试过这样做,但仍在努力使用初始化建议变量并将其“连接”到 json 的行。有什么建议吗?
    【解决方案2】:

    使用上面 saj 的建议来使用列表对象而不是数组,以下更新的方法有效。

    public ActionResult Autocomplete(string term)
            {
                var url = String.Format(" https://maps.googleapis.com/maps/api/place/autocomplete/json?input=" + term + "&types=address&location=53.4333,-7.9500&radius=250&key=MYKEY");
                var jsonautocomplete = new System.Net.WebClient().DownloadString(url);
    
                JavaScriptSerializer jss = new JavaScriptSerializer();
                Rootobject autocomplete = JsonConvert.DeserializeObject<Rootobject>(jsonautocomplete);
                var suggestions = autocomplete.predictions;
                var model = suggestions.Select(x => new
                       {
                           label = x.description
                       });
                return Json(model, JsonRequestBehavior.AllowGet);
            }
    

    【讨论】:

      猜你喜欢
      • 2016-11-11
      • 1970-01-01
      • 2019-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-07
      • 1970-01-01
      相关资源
      最近更新 更多