2016-02-02 86 views
5

我已經實現了一個方法,根據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); 
    } 
} 
+1

'type.GetType()'是錯誤的;它會給出一些從'System.Type'繼承的具體類型,這不是你想要的。你需要'if(type == typeof(Object))'那裏。在下一個'if'中,你也可以使用'=='(爲了一致性)。 –

回答

6

你可以做到這一點使用null coalescing運營商(??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); 
    } 
} 
+0

謝謝。沒有任何代表開箱即用的捷徑嗎? – Jordi

+0

謝謝西蒙!讓我問你用通用形式解決這個問題(我編輯了我的文章)。正如你可以看出,我使用一種方法來反序列化我收到的任何json字符串。因此,具體的'typeof(列表)'是C#讓我選擇的類型。 'JsonConvert.DeserializeObject(content,type)' – Jordi

相關問題