我已经实现了一种方法,根据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);
}
}
type.GetType()
是错误的;它将返回一些继承自System.Type
的具体类型,这不是你想要的。你需要用if (type == typeof(Object))
。在下一个if
中,你也可以使用==
(为了一致性)。 - Jeppe Stig Nielsen