2

I am trying to read Yelp API. Below is my code.

public async Task<HttpContent> InvokeApi(string path, HttpAction action, HttpContent content = null, TimeSpan? overrideTimeout = null, string externalServer = null)
    {

        var sUrl = externalServer == null ? ServerUrl : externalServer;

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(sUrl);
            if (overrideTimeout.HasValue)
            {
                client.Timeout = overrideTimeout.Value;
            }
            //this.Log("Connecting to {0} Api at {1}".Fmt(WebPortalServer, ServerUrl));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", AccessToken);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response;

            switch (action)
            {
                case HttpAction.Get:
                    response = await client.GetAsync(path);
                    break;
                case HttpAction.Post:
                    response = await client.PostAsync(path, content);
                    break;
                case HttpAction.Put:
                    response = await client.PutAsync(path, content);
                    break;
                case HttpAction.Delete:
                    response = await client.DeleteAsync(path);
                    break;
                default:
                    throw new ArgumentOutOfRangeException("action", action, null);
            }

            return response.IsSuccessStatusCode ? response.Content : null;
        }
    }

I am calling the above Function as

public async Task<Common.Models.Yelp.Yelp> GetAllBusiness(decimal latitude, decimal longitude)
    {
        var all = await _webPortalApiClient.InvokeApi($"businesses/search?limit=10&latitude={latitude}&longitude={longitude}", HttpAction.Get, null, null, "https://api.yelp.com/v3/");
        if (all == null)
        {
            return null;
        }

        //var business = await all.ReadAsAsync<Common.Models.Yelp.Yelp>();
        var business = all.ReadAsAsync<Object>().Result;
        var result = (Common.Models.Yelp.Yelp)(business);
        return result;
    }

The response I am getting from this api is embedded in curly braces, because of this it is not allowing me to convert response to Yelp Model.

Her is the response I get.

{{ "businesses": [ { "id": "Xg-FyjVKAN70LO4u4Z1ozg", "alias": "hog-island-oyster-co-san-francisco", "name": "Hog Island Oyster Co", "image_url": "", "is_closed": false, "url": "", "review_count": 5550, "categories": [ { "alias": "seafood", "title": "Seafood" }, { "alias": "seafoodmarkets", "title": "Seafood Markets" }, { "alias": "raw_food", "title": "Live/Raw Food" } ], "rating": 4.5, "coordinates": { "latitude": 37.795831, "longitude": -122.393303 }, "transactions": [], "price": "$$", "location": { "address1": "1 Ferry Bldg", "address2": "", "address3": "Shop 11", "city": "San Francisco", "zip_code": "94111", "country": "US", "state": "CA", "display_address": [ "1 Ferry Bldg", "Shop 11", "San Francisco, CA 94111" ] }, "phone": "+14153917117", "display_phone": "(415) 391-7117", "distance": 1154.8167382059307 }, { "id": "PsY5DMHxa5iNX_nX0T-qPA", "alias": "kokkari-estiatorio-san-francisco", "name": "Kokkari Estiatorio", "image_url": "", "is_closed": false, "url": "", "review_count": 4300, "categories": [ { "alias": "greek", "title": "Greek" }, { "alias": "mediterranean", "title": "Mediterranean" } ], "rating": 4.5, "coordinates": { "latitude": 37.796996, "longitude": -122.399661 }, "transactions": [ "pickup" ], "price": "$$$", "location": { "address1": "200 Jackson St", "address2": "", "address3": "", "city": "San Francisco", "zip_code": "94111", "country": "US", "state": "CA", "display_address": [ "200 Jackson St", "San Francisco, CA 94111" ] }, "phone": "+14159810983", "display_phone": "(415) 981-0983", "distance": 1124.9562174585888 }, { "id": "ZoZjbOYR-apY8XvommlNUA", "alias": "the-house-san-francisco", "name": "The House", "image_url": "": false, "url": "", "review_count": 4521, "categories": []}}

There is a pair of extra curly braces in the start and the end of the response. How can I fetch response in proper Json format.

3 Answers3

1

The call of

all.ReadAsAsync<Object>().Result;

returns you an instance of JObject which is not convertible to Yelp by simple cast. Instead call ReadAsAsync like this

var business = await all.ReadAsAsync<Common.Models.Yelp.Yelp>();
return business;

If you still want to call it with object you can do it like this

var business = await all.ReadAsAsync<object>();
return ((JObject)business).ToObject<Yelp>();

Note

The response json doesn't contain extra curly braces. It just JObject adds them in debug view. It is easy to check this by examining the result of reading response as a string all.ReadAsStringAsync().Result.

Alexander
  • 7,028
  • 1
  • 8
  • 28
  • actually it should be async correctly: `var business = await all.ReadAsAsync();` – Erik Philips Mar 07 '19 at 17:36
  • I tried the above solution but I get the below error { "Message": "An error has occurred.", "ExceptionMessage": "Input string '4.5' is not a valid integer. Path 'businesses[0].rating', line 1, position 634.", "ExceptionType": "Newtonsoft.Json.JsonReaderException", "StackTrace": " at Newtonsoft.Json.JsonTextReader.ParseReadNumber(ReadType readType, Char firstChar, Int32 initialPosition)\r\n at Newtonsoft.Json.JsonTextReader.ParseNumber(ReadType readType)\r\n at ....... } – Mayank Bhuvnesh Mar 08 '19 at 08:03
0

Use the JSON.NET's Deserialize method to deserialize from string into your desired POCO using the generic type overload.


public async Task<HttpContent> InvokeApi(string path, HttpAction action, HttpContent content = null, TimeSpan? overrideTimeout = null, string externalServer = null)
{

    var sUrl = externalServer == null ? ServerUrl : externalServer;

    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(sUrl);
        if (overrideTimeout.HasValue)
        {
            client.Timeout = overrideTimeout.Value;
        }
        //this.Log("Connecting to {0} Api at {1}".Fmt(WebPortalServer, ServerUrl));
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", AccessToken);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response;

        switch (action)
        {
            case HttpAction.Get:
                response = await client.GetAsync(path);
                break;
            case HttpAction.Post:
                response = await client.PostAsync(path, content);
                break;
            case HttpAction.Put:
                response = await client.PutAsync(path, content);
                break;
            case HttpAction.Delete:
                response = await client.DeleteAsync(path);
                break;
            default:
                throw new ArgumentOutOfRangeException("action", action, null);
        }

        return response.IsSuccessStatusCode ? response.Content : null;
    }
}

public async Task<Common.Models.Yelp.Yelp> GetAllBusiness(decimal latitude, decimal longitude)
{
    HttpContent all = await _webPortalApiClient.InvokeApi($"businesses/search?limit=10&latitude={latitude}&longitude={longitude}", HttpAction.Get, null, null, "https://api.yelp.com/v3/");
    if (all == null)
    {
        return null;
    }


    string responseBody = await all.ReadAsStringAsync();

    // Deserialize from serialized string into your POCO
    var business = JsonConvert.DeserializeObject<Common.Models.Yelp.Yelp>(responseBody);
    return business;
}
Kunal Mukherjee
  • 5,189
  • 3
  • 20
  • 40
-1
 var business = all.Result;  
 var resultString = business.ReadAsStringAsync();  
 return JsonConvert.DeserializeObject<Common.Models.Yelp.Yelp>(resultString);
  • 2
    Hi and welcome to Stack Overflow. It is recommended that you add more context (why the problem was there or why this works and what it is about the code that fixes the problem) to your answer for it to be more easily understood by the OP and others who come by it. – Fabulous Mar 07 '19 at 23:48