I have this generic method to parse JSON
public async Task<T> ProcessAsync<T>(HttpRequestMessage request, NamingStrategy namingStrategy)
{
if (!string.IsNullOrEmpty(_authToken))
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _authToken);
}
HttpResponseMessage response = await _client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
_logger.LogSuccess(response.StatusCode.ToString(), request.Method.ToString(), request.RequestUri.ToString());
var dezerializerSettings = new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = namingStrategy
}
};
try
{
T responseModel = JsonConvert.DeserializeObject<T>(await response.Content.ReadAsStringAsync(), dezerializerSettings);
return responseModel;
}
catch (Exception ex)
{
_logger.LogError(request.Method.ToString(), request.RequestUri.ToString(), ex);
throw;
}
}
else
{
throw await GetFailureResponseModel(response);
}
}
And this is working fine, But now I haven encountered an edge case, one of my API response contain Array in root. Like this
[
{
"productId": "100013",
"lastUpdate": "2018-02-07 15:07:09.0"
},
{
"productId": "643927",
"lastUpdate": "2018-07-05 15:25:48.0"
},
{
"productId": "699292",
"lastUpdate": "2018-07-05 15:22:24.0"
},
{
"productId": "722579",
"lastUpdate": "2018-07-05 15:20:52.0"
},
{
"productId": "722580",
"lastUpdate": "2018-07-05 15:20:53.0"
}
]
And I am getting issues parsing above JSON. This is how i am trying to parse
var response = await _client.GetAsync<FavoriteProductResponseModel>($"v2/member/favourites?total={WebUtility.UrlEncode(total)}&offset={WebUtility.UrlEncode(offset)}");
And this is my model to which I am trying to parse,
public class FavoriteProductResponseModel : BaseResponse
{
public List<FavoriteProduct> favoriteProducts { get; set; }
}
Is there any way I can parse this type of JSON with my Generic method?
FYI: As you can see my model is extended from BaseResponse, this is for Type Constraints in Generic Method. i.e
public async Task<T> GetAsync<T>(string uri, NamingStrategy namingStrategy) where T : BaseResponse
{
using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, uri))
{
return await ProcessAsync<T>(requestMessage, namingStrategy);
}
}
JsonConvert.DeserializeObjectin your current API, but the server where you request is usingJsonConvert.SerializeObject, that server should give you correct objects. my suggestion would to config that server, give you strong-typed json, then you will do nothing here. My 2nd suggestion is: by your json response, when you callGetAsync<T>, theTshould beList<FavoriteProduct>, instead of usingFavoriteProductResponseModel.