Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deserialize empty String to a List<string>

Tags:

json

c#

json.net

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);
    }
}
like image 559
Jordi Avatar asked Feb 02 '16 15:02

Jordi


1 Answers

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);
    }
}
like image 173
Simon Karlsson Avatar answered Oct 27 '22 08:10

Simon Karlsson