2016-02-02 8 views
5

Ho implementato un metodo restituisce un List<string> in base a una stringa json.deserialize stringa vuota a un elenco <string>

Sta funzionando bene ho capito che sto provando a deserializzare una stringa vuota. Non si ferma né solleva un'eccezione. Restituisce un valore null invece uno vuoto List<string>.

La domanda è: cosa posso toccare per restituire un valore vuoto List<string> invece di null?

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

EDIT metodo generico:

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()' è errato; darà del tipo concreto che eredita da 'System.Type' che non è quello che vuoi. Vuoi 'se (digita == typeof (Object))' lì. Nel prossimo 'se' puoi usare anche' == '(per coerenza). –

risposta

6

è possibile farlo utilizzando il null coalescing dell'operatore (??):

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

Si potrebbe anche farlo impostando la NullValueHandling a NullValueHandling.Ignore come questo:

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

Grazie. Non c'è una scorciatoia che si distingue per quella fuori dalla scatola? – Jordi

+0

Grazie Simon! Lascia che ti chieda di risolvere questo problema in forma generica (ho modificato il mio post). Come puoi capire, sto usando un metodo per deserializzare qualsiasi stringa json che ricevo. Quindi la specifica 'typeof (Lista )' è quella che mi consente di digitare il tipo C#. 'JsonConvert.DeserializeObject (content, type)' – Jordi

Problemi correlati