0

How can I exclude NULL entries from json. I de-serialize a string into a object list. I can access that null in that list but I want to exclude that null and stored not null rows into the list.

[ { "transactionId": 1778, "locName": "IL", }, { "transactionId": 1779, "locName": "NY", }, { "transactionId": 1774, "locName": "IL", }, { "transactionId": 1771, "locName": "NY" }, null ]

var result = JsonConvert.DeserializeObject<TList>(inputText);
NixA
  • 11
  • 7

1 Answers1

2

By default, you can't. Consider this code, which instructs JSON.NET to ignore null values:

public static void Main()
{
    var json = "[ { \"transactionId\": 1778, \"locName\": \"IL\", }, { \"transactionId\": 1779, \"locName\": \"NY\", }, { \"transactionId\": 1774, \"locName\": \"IL\", }, { \"transactionId\": 1771, \"locName\": \"NY\" }, null ]";

    var list = JsonConvert.DeserializeObject<List<Entity>>(json, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
}

public class Entity
{
    public string TransactionId { get; set; }
    public string LocName { get; set; }
}

Then list's last entry will still be null, because it's not a null value, it's a null array element.

If you wish to filter those, simply use Linq:

var nonNullList = list.Where(l => l != null).ToList();
CodeCaster
  • 147,647
  • 23
  • 218
  • 272