将空字符串反序列化为List<string>

5
我已经实现了一种方法,根据json字符串返回一个List<string>
但是当我尝试反序列化一个空字符串时,它并不会崩溃或引发异常。相反,它返回一个null值而不是一个空的List<string>
问题是,我应该怎么修改才能返回一个空的List<string>而不是null值?
return JsonConvert.DeserializeObject(content, typeof(List<string>));

编辑 通用方法:

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);
    }
}

1
type.GetType() 是错误的;它将返回一些继承自 System.Type 的具体类型,这不是你想要的。你需要用 if (type == typeof(Object))。在下一个 if 中,你也可以使用 == (为了一致性)。 - Jeppe Stig Nielsen
1个回答

7

您可以使用 null 合并 运算符 (??) 来实现:

return JsonConvert.DeserializeObject(content, typeof(List<string>)) ?? new List<string>();

你也可以通过将NullValueHandling设置为NullValueHandling.Ignore来实现:

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);
    }
}

谢谢。难道没有默认的快捷方式吗? - Jordi
谢谢Simon!让我请你以通用形式解决这个问题(我已经编辑了我的帖子)。正如你所想象的那样,我正在使用一种方法来反序列化任何我收到的JSON字符串。因此,特定的“typeof(List<string>)”是C#允许我的任何类型。JsonConvert.DeserializeObject(content, type) - Jordi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接