Property-based type resolution in JSON.NET(JSON.NET 中基于属性的类型解析)
问题描述
是否可以基于 JSON 对象的属性使用 JSON.NET 覆盖类型解析?基于现有的 API,看起来我需要一种接受 JsonPropertyCollection
并返回要创建的 Type
的方法.
Is it possible to override the type resolution using JSON.NET based on a property of the JSON object? Based on existing APIs, it looks like I need a way of accepting a JsonPropertyCollection
and returning the Type
to be created.
注意:我知道 TypeNameHandling 属性,但是添加一个 $type
属性.我无法控制源 JSON.
NOTE: I'm aware of the TypeNameHandling attribute, but that adds a $type
property. I do not have control over the source JSON.
推荐答案
这似乎是通过创建自定义 JsonConverter 并在反序列化之前将其添加到 JsonSerializerSettings.Converters
中.
It would appear that this is handled by creating a custom JsonConverter and adding it to JsonSerializerSettings.Converters
before deserialisation.
nonplus 在 JSON.NET 讨论板 在 Codeplex.我已修改示例以返回自定义 Type
并遵循默认创建机制,而不是当场创建对象实例.
nonplus has left a handy sample on the JSON.NET discussions board on Codeplex. I've modified the sample to return custom Type
and deferring to the default creation mechanism, rather than creating the object instance on the spot.
abstract class JsonCreationConverter<T> : JsonConverter
{
/// <summary>
/// Create an instance of objectType, based properties in the JSON object
/// </summary>
protected abstract Type GetType(Type objectType, JObject jObject);
public override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
JObject jObject = JObject.Load(reader);
Type targetType = GetType(objectType, jObject);
// TODO: Change this to the Json.Net-built-in way of creating instances
object target = Activator.CreateInstance(targetType);
serializer.Populate(jObject.CreateReader(), target);
return target;
}
}
这里是示例用法(也如上所述更新):
And here is the example usage (also updated as mentioned above):
class VehicleConverter : JsonCreationConverter<Vehicle>
{
protected override Type GetType(Type objectType, JObject jObject)
{
var type = (string)jObject.Property("Type");
switch (type)
{
case "Car":
return typeof(Car);
case "Bike":
return typeof(Bike);
}
throw new ApplicationException(String.Format(
"The given vehicle type {0} is not supported!", type));
}
}
这篇关于JSON.NET 中基于属性的类型解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JSON.NET 中基于属性的类型解析
基础教程推荐
- 如何激活MC67中的红灯 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- SSE 浮点算术是否可重现? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01