我已經實現了一個方法,根據json字符串返回List<string>
。將空字符串反序列化爲列表<string>
它工作得很好,我意識到我試圖反序列化一個空字符串。它不會崩潰,也不會引發異常。它返回一個null
的值,而不是一個空的List<string>
。
問題是,爲了給我返回一個空的List<string>
而不是null
的值,我可以觸摸什麼?
return JsonConvert.DeserializeObject(content, typeof(List<string>));
編輯 通用方法:通過設置NullValueHandling
到
return JsonConvert.DeserializeObject(content, typeof(List<string>)) ?? new 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'中,你也可以使用'=='(爲了一致性)。 –