Need to ignore NULL values when deserializing JSON

倖福魔咒の 提交于 2021-01-29 03:08:18

问题


I'm consuming some simple stock data in the form of JSON and plotting it on a chart. All works fine, except that some entries return NULL values because at that particular minute in time no trades were taken and therefore no price data is available. This creates gaps on the chart line.

So if the "close" value is null, I want to exclude the entire block including the "minute" and "volume" from being added into the ObservableCollection, and just move on to include the next one whose values are not null. Example JSON:

{
"minute": "10:21",  
"close": null,      
"volume": 0,
},{     
"minute": "10:22",
"close": 47.56,
"volume": 6,
}       

I have created a jsonSettings property which I have seen people talk about and claim work, yet it is not working. The code looks like this:

var jsonSettings = new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore,
            MissingMemberHandling = MissingMemberHandling.Ignore
        };

        string content = await _client.GetStringAsync(url); 
        var json_Data = JsonConvert.DeserializeObject<ObservableCollection<ChartData>>(content,jsonSettings); 
        viewModel.LineData = json_Data;

And here are my models:

public class ChartData
{
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public string minute { get; set; }

    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public double? close { get; set; }

    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public int volume { get; set; }
}

public class ViewModel
{
    public ObservableCollection<ChartData> LineData { get; set; }

    public ViewModel()
    {
        LineData = new ObservableCollection<ChartData>();
    }
}

I have tried numerous similar examples posted here and there and yet the null-value entries remain within the json_Data. Any ideas how to make it work?

Thanks!


回答1:


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);



回答2:


I believe the serialize settings are more applicable when you're "serializing", and you want to not generate JSON for properties of a class when the value is null. In this case you're deserializing, so the JSON is as it is.

Regardless, if you need to exclude this entire object because "close" is null, it doesn't matter if the property is excluded or not, you still need to check for it. What I would do as @Jason was eluding to, would be to filter separately. Something like this:

        JArray json = JArray.Parse(@"
        [{
        ""minute"": ""10:21"",  
        ""close"": null,      
        ""volume"": 0,
        },{     
        ""minute"": ""10:22"",
        ""close"": 47.56,
        ""volume"": 6,
        }]

        ");

        var filteredJson = json.Where(j => j["close"].Value<double?>() != null);


来源:https://stackoverflow.com/questions/57730528/need-to-ignore-null-values-when-deserializing-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!