gpt4 book ai didi

c# - 使用 NewtonSoft.JSON 序列化接口(interface)/抽象对象

转载 作者:太空狗 更新时间:2023-10-29 22:58:29 26 4
gpt4 key购买 nike

反序列化接口(interface)和抽象属性的一种方法是在序列化和反序列化期间将 TypeNameHandling 设置为 Auto。但是,当我在直接序列化和反序列化接口(interface)对象时尝试相同的方法时,它不起作用 -

interface ISample
{
string Key { get; set; }
}

class A : ISample
{
public string Key { get; set; }

public A(string key)
{
this.Key = key;
}
}

class B : ISample
{
public string Key { get; set; }

public B(string key)
{
this.Key = key;
}
}

序列化和反序列化代码-

ISample a = new A("keyA");
ISample b = new B("keyB");

var settings = new JsonSerializerSettings();
settings.TypeNameHandling = TypeNameHandling.Auto;

var stringA = JsonConvert.SerializeObject(a, settings);
var stringB = JsonConvert.SerializeObject(b, settings);

Console.WriteLine(stringA);
Console.WriteLine(stringB);

a = JsonConvert.DeserializeObject<ISample>(stringA, settings);
b = JsonConvert.DeserializeObject<ISample>(stringB, settings);

我注意到即使在设置 TypeNameHandling.Auto 时,序列化字符串中也不存在类型信息。但是,将 TypeNameHandling 设置为 Object 或 All 有效。

我是否遗漏了一些基本的东西?

最佳答案

要为具有 TypeNameHandling.Auto 的多态对象启用 $type 信息在根级别的输出,请使用以下重载:JsonConvert.SerializeObject Method (Object, Type, JsonSerializerSettings) .从 docs 开始:

public static string SerializeObject(
Object value,
Type type,
JsonSerializerSettings settings
)

type Type: System.Type The type of the value being serialized. This parameter is used when TypeNameHandling is Auto to write out the type name if the type of the value does not match. Specifing the type is optional.

在你的情况下,你会这样做:

var stringA = JsonConvert.SerializeObject(a, typeof(ISample), settings);
var stringB = JsonConvert.SerializeObject(b, typeof(ISample), settings);

Console.WriteLine(stringA);
Console.WriteLine(stringB);

并得到结果:

{"$type":"Tile.TestJsonDotNet.A, Tile","Key":"keyA"}
{"$type":"Tile.TestJsonDotNet.B, Tile","Key":"keyB"}

请注意 Newtonsoft docs 中的警告:

TypeNameHandling should be used with caution when your application deserializes JSON from an external source. Incoming types should be validated with a custom SerializationBinder when deserializing with a value other than None.

有关为什么这可能是必要的讨论,请参阅 TypeNameHandling caution in Newtonsoft JsonHow to configure Json.NET to create a vulnerable web API 和 Alvaro Muñoz 和 Oleksandr Mirosh 的黑帽论文 https://www.blackhat.com/docs/us-17/thursday/us-17-Munoz-Friday-The-13th-JSON-Attacks-wp.pdf

关于c# - 使用 NewtonSoft.JSON 序列化接口(interface)/抽象对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28128923/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com