我已经实现了一个方法,List<string>根据一个json字符串返回一个.
它工作得很好,我已经意识到我正在尝试反序列化一个空字符串.它不会崩溃也不会引发异常.它返回一个null值而不是空List<string>.
问题是,为了给我一个空的List<string>而不是一个null值,我可以触摸什么?
return JsonConvert.DeserializeObject(content, typeof(List<string>));
Run Code Online (Sandbox Code Playgroud)
编辑 通用方法:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
你可以使用null coalescingoperator(??)来做到这一点:
return JsonConvert.DeserializeObject(content, typeof(List<string>)) ?? new List<string>();
Run Code Online (Sandbox Code Playgroud)
你也可以通过设置做到这一点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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
993 次 |
| 最近记录: |