2
    [DataContract]
    class MyClass
    {
        [DataMember(EmitDefaultValue = false)]
        public bool Value { get; set; }

        public MyClass()
        {
            Value = true;
        }
    }
    static void Main(string[] args)
    {
        Console.WriteLine(JsonConvert.DeserializeObject<MyClass>("{\"Value\": false}").Value);
        Console.ReadKey();
    }

It will print 'True'. I think this is a bug, because I can't figure out where this scenario is valid, but how to set default value in DataMember otherwise?

eocron
  • 6,885
  • 1
  • 21
  • 50
  • Does answer in this link helpful? https://stackoverflow.com/questions/5382402/why-is-using-datamemberemitdefaultvalue-false-not-recommended (or) this: https://stackoverflow.com/questions/23742805/emitdefaultvalue-false-only-working-for-strings – sam Mar 06 '20 at 13:52
  • 1
    This seems to be a bug in the implementation of handling of DataMember support in Json.net. The `EmitDefaultValue` property should only be used when serializing, not when deserializing. The value in the json should be put into the property regardless of what it is. – Lasse V. Karlsen Mar 06 '20 at 13:55
  • 1
    Unfortunately it now seems this "bug" is by design - https://github.com/JamesNK/Newtonsoft.Json/issues/88 - I asked a question in the comment thread on that issue, let's see if I get a response. I still maintain that this is a bug, it should only affect **serialization** and not *deserialization*. – Lasse V. Karlsen Mar 06 '20 at 14:06
  • I agree, created new ticket for clearance - https://github.com/JamesNK/Newtonsoft.Json/issues/2294 – eocron Mar 06 '20 at 14:06
  • 1
    I moved my comment to your new issue. – Lasse V. Karlsen Mar 06 '20 at 14:09

0 Answers0