How to get Json Data from an external WEB API to an JQUery autosearch text box end point

Jose Daniel Navarro Brito 61 Reputation points
2025-01-10T16:24:18.3033333+00:00

Hi everybody:

I have an external minimal Web API that produces a JSON object ( array) as per below.

app.MapGet("/AsyncAutocompleteErf/{search}", async (IErvenRepository request,  string search) =>
{
    var data = await request.GetSearchedErfNumberAsync(search);
    if (data == null)
        return Results.NotFound("Sorry, there are not records");
    return Results.Ok(data);
}).WithName("AsyncAutocompleteErf");

The method executes an SQL procedure returning a JSon array with the following structure

[
  {
    "value": "1",
    "label": "15209 =>Gugulethu Infill Housing "
  }
]


Then, I have and end point application that calls the above API method as per below

   public async Task<string> AutoComplete(string search)
   {
       IEnumerable<AutoSearchViewModel> apiResponseBody = null;
       {
           var httpClient = _httpClientFactory.CreateClient("HousingWebAPI");
           using (var response = await httpClient.GetAsync("AsyncAutocompleteErf/" + search))
           {
               if (response.IsSuccessStatusCode)
               {
                   
                   var content = await response.Content.ReadAsStringAsync();
                 
                   return (content);
                  
               }
           }
       }
       return null;
   }

Up to this point, I''m using ReadAsStringAsync the HTTp response ( the JSON array) to an string in order to "feed"the value, label items that the Jquery autocmplete drop down box needs ( my understanding).

Accordingly, I have a javascript function hooked up to this procedure.

<script type="text/javascript">
    $(function () {
        $("#txtCustomer").autocomplete({
             minLength: 2,
          
            source: function (request, response) {
                $.ajax({
                    url: '/Erf/AutoComplete/',
                    data: { "search": request.term},
                    dataType: "json",
                    type: "GET",
                    sucess:function(data)
                          {response((data));
                    },                       
                    error: function (response) {
                        alert(response.responseText);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    }
                });
            },
        });
    });
</script>

When I run the Javascript function everything fires up and the HTTP response is of course a string with the following structure [{"value":"1","label":"15209 =>Gugulethu Infill Housing "}]

The autocomplete target doesn't load any data so I assume that converting the JSON array to a string is not the way to go. I tried to return a JSON via JSONResult Action Task ( see below) but the JSon response is like this => "[{\u0022value\u0022:\u00221\u0022,\u0022label\u0022:\u002215209 =\u003EGugulethu Infill Housing \u0022}]"

  [HttpGet]
  
   public async Task<JsonResult> AutoComplete(string search)
   {
       IEnumerable<AutoSearchViewModel> apiResponseBody = null;
       {
           var httpClient = _httpClientFactory.CreateClient("HousingWebAPI");
           using (var response = await httpClient.GetAsync("AsyncAutocompleteErf/" + search))
           {
               if (response.IsSuccessStatusCode)
               {
                   
                   var content = await response.Content.ReadAsStringAsync();
                 
                   return Json(content);
                  
               }
           }
       }
       return null;
   }

Can anybody assist me please? Also ..is it right to use GET instead of Post for the purpose of loading a jquery autocomplete text box?

Thanks in advance

Developer technologies | ASP.NET | ASP.NET Core
Microsoft 365 and Office | Development | Office JavaScript API
Developer technologies | ASP.NET | ASP.NET API
{count} votes

4 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 79,101 Reputation points Volunteer Moderator
    2025-01-10T17:25:46.89+00:00

    it you look at the response in the browser debug tools the json string is probably encoded, because the AutoComplete action returned a string that is converted to a json. for example:

    the string value [{"value":1}] when converted to json is: "[{\"value\":1}]"

    the method Json is expecting an object to convert, not a string that contain Json Data. you ned to return content of type "application/json".

           var content = await response.Content.ReadAsStringAsync();
           return Context(content,"application/json");
    

  2. SurferOnWww 4,811 Reputation points
    2025-01-11T06:23:24.1066667+00:00

    Are you saying that your Web API returns JSON string [{\u0022value\u0022:\u00221\u0022,\u0022label\u0022:\u002215209 =\u003EGugulethu Infill Housing \u0022}] although you are expecting [{"value":"1","label":"15209 =>Gugulethu Infill Housing "}] ?

    If so it is probably the result of Unicode Escape Sequence (UES). Please refer to the following Microsoft document:

    Serialization behavior

    "The default encoder escapes non-ASCII characters, HTML-sensitive characters within the ASCII-range, and characters that must be escaped according to the RFC 8259 JSON spec."

    The characters " and > in [{"value":"1","label":"15209 =>Gugulethu Infill Housing "}] belong to the HTML-sensitive characters within the ASCII-range. Therefore, they were converted to \u0022 and \u003E.

    UES is character expression in the form of \uxxxx where xxxx is Unicode of such character:

    enter image description here


  3. Anonymous
    2025-01-13T09:18:20.49+00:00

    Hi @Jose Daniel Navarro Brito,

    You can use the code like below:

    var httpClient = _httpClientFactory.CreateClient("HousingWebAPI");
    using (var response = await httpClient.GetAsync("AsyncAutocompleteErf/" + search))
    {
        if (response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            var apiResponseBody = JsonConvert.DeserializeObject<IEnumerable<AutoSearchViewModel>>(content);
            return Json(apiResponseBody); // Return the deserialized object
        }
    }
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Rena

    0 comments No comments

  4. Raymond Huynh (WICLOUD CORPORATION) 620 Reputation points Microsoft External Staff
    2025-07-28T07:56:44.26+00:00

    Hi @Jose Daniel Navarro Brito ,

    Looking at your jQuery autocomplete issue, I can see the problem clearly. You're getting double-encoded JSON because you're treating JSON as a string when it should be handled as an object.

    Here's what's happening and how to fix it:

    Your API returns proper JSON, but you're converting it to a string with ReadAsStringAsync(), then trying to return that string as JSON again. This creates the double-encoding you're seeing.

    You need to deserialize the JSON string back into an object, then return that object as JSON:

    [HttpGet]
    public async Task<JsonResult> AutoComplete(string search)
    {
        var httpClient = _httpClientFactory.CreateClient("HousingWebAPI");
        using (var response = await httpClient.GetAsync("AsyncAutocompleteErf/" + search))
        {
            if (response.IsSuccessStatusCode)
            {
                var jsonString = await response.Content.ReadAsStringAsync();
                var data = JsonConvert.DeserializeObject<List<AutoSearchViewModel>>(jsonString);
                return Json(data);
            }
        }
        return Json(new List<AutoSearchViewModel>()); // Return empty array instead of null
    }
    

    Why this works:

    • Your external API returns valid JSON
    • You deserialize it into C# objects
    • You return those objects as JSON using Json()
    • jQuery receives proper JSON objects, not encoded strings

    Regarding GET vs POST:

    GET is perfectly fine for autocomplete. You're just retrieving data based on a search term, which is exactly what GET is designed for. POST would be overkill here.

    Hope this helps!


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.