将原始JSON字符串存储在反序列化的JSON.NET对象中 [英] Storing original JSON string in deserialised JSON.NET objects
问题描述
这基本上是问题 Newtonsoft对象的后续→获取JSON字符串.
我有一个看起来像这样的对象:
I have an object that looks like this:
[JsonConverter(typeof(MessageConverter))]
public class Message
{
public Message(string original)
{
this.Original = original;
}
public string Type { get; set; }
public string Original { get; set; }
}
我的要求是在初始化时将原始JSON字符串存储为对象的一部分.我已经能够(部分)使用自定义的 JsonConverter
成功实现了这一目标,然后基本上在 JsonConverter
中做到了这一点:
My requirement is to store the original JSON string as part of the object when I initialise it. I have been able to (partially) successfully achieve this using a custom JsonConverter
and then basically doing something like this in the JsonConverter
:
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == Newtonsoft.Json.JsonToken.Null)
return null;
JObject obj = JObject.Load(reader);
return new Message(obj.ToString(Formatting.None))
{
Type = obj["type"].ToString()
};
}
但是我遇到的问题是当我尝试从
However the problem I run into is when I try to inherit from Message
with something like
public class CustomMessage : Message
{
public string Prop1 { get; set; }
}
出于明显的原因,我的代码失败,因为它试图返回一个新的 Message()
而不是一个新的 CustomMessage()
.
For obvious reasons my code fails because it tries to return a new Message()
not a new CustomMessage()
.
缺少对所有子类型实现大型if语句并使用 JObject ["prop"].ToObject< T>()
之类的方法进行手动绑定的方法,我该如何成功填充 Original
属性,同时仍使用默认的反序列化绑定我的所有子类型值?
So short of implementing a big if statement with all my sub-types and manually binding using something like JObject["prop"].ToObject<T>()
how can I successfully populate the Original
property while still binding all my sub-type values using the default deserialisation?
注意:之所以这样做,是因为原始消息可能包含未实际绑定的数据,所以我不能仅添加一个将对象按原样序列化的属性./em>
推荐答案
我将问题悬而未决,希望有人能提供更好的答案,但我暂时使用了以下解决方案来解决我的问题.
I'm leaving the question open in the hope that someone comes up with a better answer but I've temporarily used the following solution to resolve my problem.
public static class MessageExtensions
{
public static T Deserialize<T>(this string message) where T : Message
{
T instance = Activator.CreateInstance<T>();
instance.Original = message;
JsonConvert.PopulateObject(message, instance);
return instance;
}
}
这篇关于将原始JSON字符串存储在反序列化的JSON.NET对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!