当将specifc类强制转换为其他对象时,JsonSerializer的行为与预期的不同 [英] JsonSerializer behaves not as expected when the specifc class is casted to something else

查看:106
本文介绍了当将specifc类强制转换为其他对象时,JsonSerializer的行为与预期的不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从json.net迁移到Microsoft的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的序列化程序从IName序列化属性 JSON.NET序列化Person的属性

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

是否有一种配置它的方式使其可以像JSON.NET一样工作?我可以通过的选项并不表示这是可配置的.我有事吗

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);
}

这会将typeof(IName)传递给WriteCoreString,并最终对该类型执行反射.

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());

这将返回:

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

也可以使用object进行铸造,因为代码

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

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

这篇关于当将specifc类强制转换为其他对象时,JsonSerializer的行为与预期的不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆