0

I have a class in my ASP.NET MVC project which calls the Google MAPS Autocomplete 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);
    }

This is to create a call to the Google MAPS API which dynamically creates a URL to the API based the value which is in turn passed into the function as term).

I also have supporting classes in the same controller to deserialise (not sure this is the correct term) the returned 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; }
}

I can see that this is correctly returning JSON formatted data which contains the address suggestions but I am having issues with deserialising it correctly

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

HOWEVER

The suggestions string is null (it should contain the returned suggestions from parsing the JSON from Google MAPS and taking the description attributes- the API returns the best 5 matches) and Visual Studio throws an out of range exception.

I am fairly sure the error lies in this line of code which is not deserialising the JSON correctly.

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

I am trying to pass these values through into a JQUERY function on the Index view of the Entity that this controller relates to as follows:

<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>

The JSON being returned needs to contain values that in something like the following format

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

Apologies if the JSON format above is not exact, just trying to show which of the longer list of the JSON attributes coming back from the Google MAPS API I'm interested in autofilling to the form.

As you'll see above these are the "description" attributes in the JSON originally returned

I would be very grateful for advice on how to correctly update this line to grab the right values:

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

Thank you

2 Answers 2

1

try using lists instead of arrays in your class http://json2csharp.com/

PS, VS paste special as classes does the same thing.(deserialize is correct)

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; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hi saj Thanks for your reply. I've tried doing that but am still struggling with the line which initialises the suggestions variable and "wires it up" to the json. Any suggestions?
0

Using saj's suggestion above to use a list object and not an array, the following updated method works.

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);
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.