Deserialize empty string to list <string>

I have implemented a method that returns a List<string> according to a json string.

It works fine, and I realized that I'm trying to deserialize an empty string. This is not a failure, but an exception. It returns null instead of an empty List<string> .

The question is, what can I touch to return me an empty List<string> instead of null ?

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

EDIT General method:

 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); } } 
+5
source share
1 answer

You can do this using the null coalescing ( ?? ) operator:

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

You can also do this by setting NullValueHandling to NullValueHandling.Ignore as follows:

 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); } } 
+6
source

Source: https://habr.com/ru/post/1242102/


All Articles