yt2008
yt2008

Reputation: 3

Newtonsoft JsonConvert DeserializeObject cannot ignore Default Value from entity err?

Here is the Sample code:

I have a TargetEntity which contains a bool list, by default, it is set to a seven elements list of true value.

What I am trying to do is deserialize from JSON, which contains a list of seven false value. However, when deserializing it, it seems constructed a list of 14 values, which included the default ones and attached the deserialized from the JSON like this { true, true, true, true, true, true, true, false, false, false, false, false, false, false } What is wrong here?

using Newtonsoft.Json;
using System.Collections.Generic;


public class Program
{
    public static void Main()
    {
        var _entityList = JsonConvert.DeserializeObject<List<TargetEntity>>(
            "[{\"BoolsList\": [false,false,false,false,false,false,false]}]",
            new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });

        Console.WriteLine("List size: " + _entityList[0].BoolsList.Count);

        for(int i = 0; i < _entityList[0].BoolsList.Count; i++)
        {
            Console.WriteLine($"List element {i}: " + _entityList[0].BoolsList[i]);
        }
        
    }

    public class TargetEntity 
    {
        public List<bool> BoolsList { get; set; } = new List<bool> { true, true, true, true, true, true, true };
    }

}

There is C# fiddle like for this code: https://dotnetfiddle.net/VMIXeg

Upvotes: 0

Views: 533

Answers (1)

nunohpinheiro
nunohpinheiro

Reputation: 2269

It is a very interesting behavior, related with the serializer settings and the way the new object is constructed and populated :)

If what you want is to replace the default list and keep on using Newtonsoft.Json, you can replace the settings

new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore }

by

new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace }

Depending on your .NET version, you may also use System.Text.Json:

using System;
using System.Collections.Generic;
using System.Text.Json;

public class Program
{
    public static void Main()
    {
        var _entityList = JsonSerializer.Deserialize<List<TargetEntity>>("[{\"BoolsList\": [false,false,false,false,false,false,false]}]");
        ...
    }
...
}

Upvotes: 2

Related Questions