I'm using Json.Net to parse JSON into my app logic. The problem is that the external API that I get the JSON from sometimes has "null" items inside their lists. I would like to remove those "null" items from the list (or any other IEnumerable that might have that) at parse time. I believe the solution has to be using a JsonConverter but I was unable to get it working so far.
MyData data = new MyData();
Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings
{
Converters = new List<JsonConverter>() { new TrimNullListValues() }
};
string jsonString = @"{""ListData"": [{""source"" : 10 , ""target"" : 20, ""Data"" : [{""source"" : 100 , ""target"" : 200}, null]}, null]}";
JsonConvert.PopulateObject(jsonString, data, settings);
MyData class is like this:
public class MyData {
public class MyNestedData
{
public int Source;
public int Target;
public List<MyNestedData> Data;
}
public List<MyNestedData> ListData;
}
My JsonConverter (TrimNullListValues) is like this:
public class TrimNullListValues : JsonConverter {
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// Don't really know what to do in here to remove unwanted values
// From the IEnumerabes
}
public override bool CanConvert(Type objectType)
{
return objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(List<>);
}
}