How to serialize object to json with type info using Newtonsoft.Json?(如何使用 Newtonsoft.Json 将对象序列化为带有类型信息的 json?)
问题描述
当我序列化某些类型的对象时,我希望在 JSON 中有一个类型名称为类型的属性.我写了一个转换器:
I want to have a property with type name in JSON when I serialize objects of certain types. I wrote a converter:
public class TypeInfoConverter : JsonConverter {
private readonly IEnumerable<Type> _types;
public TypeInfoConverter(IEnumerable<Type> types) {
Contract.Requires(types != null);
_types = types;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
var jObject = JObject.FromObject(value, serializer);
jObject.AddFirst(new JProperty("Type", value.GetType().Name));
jObject.WriteTo(writer);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
return serializer.Deserialize(reader, objectType);
}
public override bool CanConvert(Type objectType) {
return _types.Any(t => t.IsAssignableFrom(objectType));
}
}
但是当我尝试序列化对象时,我在这里有一个无限递归:var jObject = JObject.FromObject(value, serializer);
这很明显,因为我使用了与该转换器配置的相同 JsonSerializer 实例.
But when I'm trying to serialize object I have an infinity recursion here:
var jObject = JObject.FromObject(value, serializer);
It is obvious because I use the same instance of JsonSerializer which was configured with that converter.
如何防止使用这个转换器,但是我想使用为这个序列化器配置的其他转换器?
How to prevent using this converter, but I want to use other converters which configured for this serializer?
我要序列化的类型:
public interface ITaskResult {
}
public class UserHasRejectedOffer : ITaskResult {
public string Message { get; set; }
}
public class UserHasFilledForm : ITaskResult {
public string FormValue1 { get; set; }
public string Formvalue2 { get; set; }
}
...
推荐答案
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
var converters = serializer.Converters.Where(x => !(x is TypeInfoConverter)).ToArray();
var jObject = JObject.FromObject(value);
jObject.AddFirst(new JProperty("Type", value.GetType().Name));
jObject.WriteTo(writer, converters);
}
这篇关于如何使用 Newtonsoft.Json 将对象序列化为带有类型信息的 json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 Newtonsoft.Json 将对象序列化为带有类型信息的 json?
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 使用 rss + c# 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01