Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unexpected error when deserializing unknown types #1266

Closed
blair-ahlquist opened this issue Mar 30, 2017 · 1 comment
Closed

Unexpected error when deserializing unknown types #1266

blair-ahlquist opened this issue Mar 30, 2017 · 1 comment

Comments

@blair-ahlquist
Copy link

blair-ahlquist commented Mar 30, 2017

In the following code, I serialize an object using Json.Net. This Json has type names embedded. I then change one of the type names to induce an error. When I deserialize the Json, I expect to get an object back that has a null value for the property with the fiddled type name. Instead the serializer craps out and returns null for the root object. The second error that I get suggests that there is a bug in the serializer.

static public class JsonTest
{
    static public void Test()
    {
        // Create test object
        A a = new A
        {
            MyTest = new MyTest(),
        };
      
        // Serialize it. 
        string json = JsonConvert.SerializeObject(a, new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.Auto
        });

        // Fiddle class name to induce error
        json = json.Replace("+MyTest", "+MyTest2"); 

        // Before: {"MyTest":{"$type":"<Namespace>.JsonTest+MyTest, <Assembly>"}}
        // After: {"MyTest":{"$type":"<Namespace>.JsonTest+MyTest2, <Assembly>"}}

        // Deserialize
        A a2 = JsonConvert.DeserializeObject<A>(json, new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.Auto,
            Error = (object sender, ErrorEventArgs e) =>
            {
                e.ErrorContext.Handled = true; // Should have only one error: the unrecognized Type
            }
        });

        // A second error occurs: Error = {Newtonsoft.Json.JsonSerializationException: Additional text found in JSON string after finishing deserializing object....
        // a2 is null
    }

    public class A
    {
        public ITest MyTest { get; set; }
    }

    public interface ITest { }
    public class MyTest : ITest { }
}

(This was posted as a question on stackoverflow.)

@JamesNK
Copy link
Owner

JamesNK commented Apr 1, 2017

Fixed f88ae28

@JamesNK JamesNK closed this as completed Apr 1, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants