Nikita Goncharuk
Nikita Goncharuk

Reputation: 815

C#, Json deserialization: avoid empty string array elements

My json array, which comes to me from the server, can contain empty string elements. I want to remove them at the level of deserialization.

{
   "Highlights":[
         "Þingvellir National Park",
         "Gullfoss Waterfall",
         "Geysir Geothermal Area",
         "Laugarvatn","Kerið Crater",
         "Hveragerði Hot Spring Area",
         "",
         ""
   ]
}

Model:

public class TestModel
{
    public List<string> Highlights { get; set; }
}

I want that if the element is string.IsNullOrEmpty (element) == true, then it is not added to the array.

In this case, the number of elements after deserialization in the TestModel.Highlights array should be 6, not 8, because 2 of them are empty.

How can I achieve this?

Upvotes: 1

Views: 1168

Answers (1)

LeviTheOne
LeviTheOne

Reputation: 105

The simple way is to iterate trough the collection and check for null or empty strings as suggested in comments. The harder and ugly(for this situation) way would be to create a custom JsonConverter based on this answer like:

class IgnoreEmptyItemsConverter<T> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType.IsAssignableFrom(typeof(List<T>));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        List<T> list = new List<T>();
        JArray array = JArray.Load(reader);
        foreach (var obj in array)
        {
            // really custom way (not really generic)
            if (!String.IsNullOrEmpty(obj.ToString()))
            {
                list.Add(obj.ToObject<T>(serializer));
            }
        }
        return list;
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

and this can be used in your model like:

public class RootObject
{
    [JsonConverter(typeof(IgnoreEmptyItemsConverter<string>))]
    public List<string> Highlights { get; set; }
}

Upvotes: 1

Related Questions