Conditional serialization Newtonsoft Json Serialization Unexpectedly

I ran into an odd issue when the unexpected serialization of Newtonsoft Json unexpectedly started. I overdid it to a simple example (we use newtonsoft json 5.0.8):

public class TestClass
{
    public string Foo { get; set; }
    public bool FooSpecified { get; set; }
    public TestClass()
    { }
    public TestClass(string foo, bool spec)
    {
        Foo = foo;
        FooSpecified = spec;
    }
}

class Program
{
    static void Main(string[] args)
    {
        TestClass test1 = new TestClass("foo", false);
        string serial1 = JsonConvert.SerializeObject(test1);
        Console.WriteLine("Test 1: {0}", serial1);

        TestClass test2 = new TestClass("bar", true);
        string serial2 = JsonConvert.SerializeObject(test2);
        Console.WriteLine("Test 2: {0}", serial2);
    }
}

The result is higher:

Test 1: {"FooSpecified":false}
Test 2: {"Foo":"bar","FooSpecified":true}

It seems that having a bool property named "xSpecified", where "x" matches the name of another property, acts like conditional serialization. I did not find this documented anywhere in the Newtonsoft json conditional serialization docs ( http://james.newtonking.com/json/help/index.html?topic=html/ConditionalProperties.htm ) and none of them showed other hits for of this behavior.

Does anyone know if this is the expected behavior or I hit some kind of error?

+4
1

, . , , . , .

TestClass test1 = new TestClass("foo", false);
string serial1 = JsonConvert.SerializeObject(test1);
test1.FooSpecified = true;
string serial3 = JsonConvert.SerializeObject(test1);
Console.WriteLine("Test 1: {0}", serial1);
Console.WriteLine("Test 1: {0}", serial3);

, , , XmlSerializer, propertyNameSpecified . , JNK, , , , , , .

http://json.codeplex.com/workitem/19091

EDIT: LB, , ; https://github.com/ayoung/Newtonsoft.Json/blob/master/Newtonsoft.Json/Serialization/JsonTypeReflector.cs

, codeplex, . JNK , , , - . - - , . , JNK .

+2

Source: https://habr.com/ru/post/1531235/


All Articles