JsonSerializer behaves not as expected when the specifc class is casted to something else

the json value could not be converted to system string
c# json to object
system text json

Im trying to migrate from json.net to microsoft's json and found something that behaves very differently.

Let's use this simplified example:

public interface IName
{
    string Name { get; set; }

}

public class Person : IName
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public void Foo() 
{
   IName p = new Person {Age = 4, Name = "Waldo"};
   var s1 = System.Text.Json.JsonSerializer.Serialize(p); // --> {"Name":"Waldo"}
   var s2 = Newtonsoft.Json.JsonConvert.SerializeObject(p); // --> {"Name":"Waldo","Age":4}
}

Microsoft's Serializers serializes properties from IName JSON.NET serializes properties from Person

Is there a way to configure it so that it would work like JSON.NET? The options that I could pass do not indicate that this is configurable. Did I overlook something?


This is because the serializer uses the type of the generic parameter, not the type of the passed value:

public static string Serialize<TValue>(TValue value, JsonSerializerOptions options = null)
{
    return WriteCoreString(value, typeof(TValue), options);
}

This passes typeof(IName) to WriteCoreString, and on that type ultimately reflection is performed.

You can work around this by explicitly passing the type to the overload that accepts that:

var s3 = System.Text.Json.JsonSerializer.Serialize(p, p.GetType());

This returns:

{"Name":"Waldo","Age":4}

Casting to object also works, as the code then calls value.GetType():

var s4 = System.Text.Json.JsonSerializer.Serialize((object)p);

Recently Active 'json.net' Questions - Page 2, JsonSerializer behaves not as expected when the specifc class is casted to something else · c# json json.net .net-core-3.0 system-text-json · Jan 3 at 18:46  type JsonSerializer = class Public Class JsonSerializer Inheritance. Object. JsonSerializer. Remarks. For more information, see How to serialize and deserialize JSON.


Newtonsoft.Json.JsonConvert.SerializeObject is a non-generic method so that it analyzes the provided object at runtime and serializes all properties that the object has.

In comparison System.Text.Json.JsonSerializer.Serialize(p) is resolved to a generic method. The compiler infers the type parameters based upon the type of the variable, in the case of your same IName. Therefore, the method analyzes the provided type and exports the properties of the generic type parameter, not all properties of the object that implements the interface.

The documentation shows that the serialize method always needs to be given a type, either through the generic type parameter or as a parameter to the method.

The following code should fixes the behavior:

var s1 = System.Text.Json.JsonSerializer.Serialize(p, p.GetType()); 
// --> {"Name":"Waldo","Age":4}

See this sample.

json, JsonSerializer behaves not as expected when the specifc class is casted to something else. 3-3-2020 json json Flutter - error no such file or directory when reading JSON file. 3-3-2020 json json How do I connect two blocks using no more than 3 lines in JavaScript? Something like the onet connect game. Working on a  What behavior is expected here? Should the serializer replace the original collection? From my point of view if there is something in the collection it must not be overwritten, only added to it. Since arrays doesn't support addition there is no way to insert a value without replacing the whole array.


Gson User Guide - gson, JsonSerializer behaves not as expected when the specifc class is casted to something else Flutter - error no such file or directory when reading JSON file. CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100


I think what you need is to pass the reference of the object to the method

        IName p = new Person { Age = 4, Name = "Waldo" };
        var s1 = System.Text.Json.JsonSerializer.Serialize<Person>((Person)p);

For .NET Core 3.0

CA2329: Do not deserialize with JsonSerializer using an insecure , JsonSerializer behaves not as expected when the specifc class is casted to something else. Im trying to migrate from json.net to microsoft's json and found  The OnErrorAttribute works much like the other .NET serialization attributes that Json.NET supports. To use it you simply place the attribute on a method that takes the correct parameters: a StreamingContext and an ErrorContext.


Casting vs “as” – embracing exceptions, However, Gson can not automatically deserialize the pure inner classes since their You can serialize the collection with Gson without doing anything specific: registerTypeAdapter call checks if the type adapter implements more than one of Well-behaved classes that are meant for serialization and deserialization  The code then calls the Customer class's FromJson method to deserialize the serialization and create a new Customer object. It finishes by using the new object's ToString method to show its properties in the txtProperties TextBox. This example may seem complicated, but it's actually not too bad.


sqlalchemy.sql.sqltypes, The TypeNameHandling property is a value other than None . JsonSerializer instances that are configured to deserialize types specified from input, Json; public class BookRecord { public string Title { get; set; } public object Location If the type isn't expected, then stop deserialization. if (typeName != In a previous post we saw how to create a custom JSON serializer (and also a custom deserializer) with Jackson and how to register it using the SimpleModule class. This approach, only possible starting from version 1.7, is defined by Jackson wiki page as the “recommended way to register a custom serializer”.


This post will not go into all of those – it would be enormous – just two of them, in one specific situation. which isn't compatible with Button, the two behave differently: We can do this with the cast as well, using the "is" operator: Aside from anything else, it's only performing a single execution-time type  Serializing a class that implements an interface is simple. Deserializing JSON to one of many possible classes that implement an interface can be tricky business. Json.NET (otherwise known as Newtonsoft Json) provides an easy option to handle this situation, but this option is not as robust as may sometimes be necessary.