考虑到您没有字段来确定要转换为哪种具体类型,您唯一的解决方案就是您所说的,TypeNameHandling = TypeNameHandling.Objects
.
但是,您可以减轻安全漏洞。
使用自定义ISerializationBinder https://www.newtonsoft.com/json/help/html/SerializationSettings.htm#SerializationBinder在序列化期间将 .NET 类型解析为类型名称以及反序列化期间将类型名称解析为 .NET 类型时验证传入类型名称:
ConsoleAppSerializationBinder.cs
public class ConsoleAppSerializationBinder : ISerializationBinder
{
public Type BindToType(string? assemblyName, string typeName)
{
var resolvedTypeName = $"{typeName}, {assemblyName}";
return Type.GetType(resolvedTypeName, true);
}
public void BindToName(Type serializedType, out string? assemblyName, out string? typeName)
{
assemblyName = null;
typeName = serializedType.AssemblyQualifiedName;
}
}
Set the SerializationBinder
您的财产JsonSerializerSettings object https://www.newtonsoft.com/json/help/html/SerializationSettings.htm到绑定器的实例,并使用与最初反序列化数据相同类型的绑定器进行反序列化。
var jsonSerializerSettings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects,
SerializationBinder = new ConsoleAppSerializationBinder()
};
这是一些演示工作代码来演示用法:
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var jsonSerializerSettings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects,
SerializationBinder = new ConsoleAppSerializationBinder()
};
var something1Input = new Foo
{
Number = 1,
Thing = new Something1
{
RandomNumber = 1,
RandomString = "test"
}
};
var something2Input = new Foo
{
Number = 1,
Thing = new Something2
{
RandomNumber = 2,
RandomBool = true
}
};
var something1Json = JsonConvert.SerializeObject(something1Input, jsonSerializerSettings);
var something2Json = JsonConvert.SerializeObject(something2Input, jsonSerializerSettings);
var something1 = JsonConvert.DeserializeObject<Foo>(something1Json, jsonSerializerSettings);
var something2 = JsonConvert.DeserializeObject<Foo>(something2Json, jsonSerializerSettings);
Console.WriteLine(something1.Thing.GetType());
Console.WriteLine(something2.Thing.GetType());
}
public class Foo
{
public int Number { get; set; }
public ISomething Thing { get; set; }
}
public interface ISomething
{
public int RandomNumber { get; set; }
}
public class Something1 : ISomething
{
public int RandomNumber { get; set; }
public string RandomString { get; set; }
}
public class Something2 : ISomething
{
public int RandomNumber { get; set; }
public bool RandomBool { get; set; }
}
public class ConsoleAppSerializationBinder : ISerializationBinder
{
public Type BindToType(string? assemblyName, string typeName)
{
var resolvedTypeName = $"{typeName}, {assemblyName}";
return Type.GetType(resolvedTypeName, true);
}
public void BindToName(Type serializedType, out string? assemblyName, out string? typeName)
{
assemblyName = null;
typeName = serializedType.AssemblyQualifiedName;
}
}
}
}
Output:
ConsoleApp.Program+Something1
ConsoleApp.Program+Something2