I've implemented a method returns a List<string>
according to an json string.
It's working well up to I've realized that I'm trying to deserialize an empty string. It doesn't crash neither raises an exception. It returns a null
value instead an empty List<string>
.
The question is, what could I touch in order to returns me an empty List<string>
instead a null
value?
return JsonConvert.DeserializeObject(content, typeof(List<string>));
EDIT Generic method:
public object Deserialize(string content, Type type) {
if (type.GetType() == typeof(Object))
return (Object)content;
if (type.Equals(typeof(String)))
return content;
try
{
return JsonConvert.DeserializeObject(content, type);
}
catch (IOException e) {
throw new ApiException(HttpStatusCode.InternalServerError, e.Message);
}
}
You can do it using the null coalescing
operator (??
):
return JsonConvert.DeserializeObject(content, typeof(List<string>)) ?? new List<string>();
You could also do it by setting the NullValueHandling
to NullValueHandling.Ignore
like this:
public T Deserialize<T>(string content)
{
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
};
try
{
return JsonConvert.DeserializeObject<T>(content, settings);
}
catch (IOException e)
{
throw new ApiException(HttpStatusCode.InternalServerError, e.Message);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With