Deserialize Json in C# - How to Handle Null Return Values

Deserialize Json in C# - How to Handle null Return Values

Try to use nullable type

public string? name;

How to handle null/empty values in JsonConvert.DeserializeObject

You can supply settings to JsonConvert.DeserializeObject to tell it how to handle null values, in this case, and much more:

var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
};
var jsonModel = JsonConvert.DeserializeObject<Customer>(jsonString, settings);

Need to ignore NULL values when deserializing JSON

NullValueHandling.Ignore will ignore null values for the relevant property of your model when serializing.

When deserialzing, you might consider deserializing to an IEnumerable<ChartData> then using Linq to filter out the objects you don't want, based on what is, after all, custom logic: "exclude objects that have close == null".

E.g. (untested air code):

var data = JsonConvert.DeserializeObject<IEnumerable<ChartData>>(content,jsonSettings)
.Where(cd => cd.close != null)
;

var observableData = new ObservableCollection<ChartData>(data);


Related Topics



Leave a reply



Submit