gpt4 book ai didi

c# - 使用 JsonConvert.DeserializeObject 反序列化派生对象列表

转载 作者:行者123 更新时间:2023-11-30 15:32:25 28 4
gpt4 key购买 nike

我有这个对象

public class ConversationAPI
{
[JsonProperty(PropertyName = "lU")]
public DateTime LastUpdated { get; set; }

[JsonProperty(PropertyName = "m", TypeNameHandling = TypeNameHandling.All)]
public List<Message> Messages { get; set; }
}

我从 API 作为 json 发送,并在我的客户端应用程序中反序列化。

The List<Message> Messages property contains either 

[Serializable]
public class Message
{
[JsonProperty(PropertyName = "t")]
public string Text { get; set; }

[JsonProperty(PropertyName = "ty")]
public MessageType Type { get; set; }
}

[Serializable]
public class DerivedMessage : Message
{
[JsonProperty(PropertyName = "sos")]
public string SomeOtherStuff{ get; set; }
}

我似乎无法反序列化派生类型数组。这个我试过了

var settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Full
};
var conversation = JsonConvert.DeserializeObject<ConversationResponse>(response.Content, settings);

我希望 List Messages 同时具有 MessageDerivedMessage 对象。

有什么想法吗?谢谢

最佳答案

找到解决方案。我使用了自定义转换器

public class MessageConverter : JsonCreationConverter<ConversationAPI.Message>
{
private const string SomeOtherStuffField = "sos";

protected override ConversationAPI.Message Create(Type objectType, JObject jObject)
{
if (FieldExists(SomeOtherStuffField , jObject))
{
return new ConversationAPI.DerivedMessage ();
}

return new ConversationAPI.Message();
}

private bool FieldExists(string fieldName, JObject jObject)
{
return jObject[fieldName] != null;
}
}

public abstract class JsonCreationConverter<T> : JsonConverter
{
/// <summary>
/// Create an instance of objectType, based properties in the JSON object
/// </summary>
/// <param name="objectType">type of object expected</param>
/// <param name="jObject">contents of JSON object that will be deserialized</param>
/// <returns></returns>
protected abstract T Create(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)
{
// Load JObject from stream
JObject jObject = JObject.Load(reader);

// Create target object based on JObject
T target = Create(objectType, jObject);

// Populate the object properties
serializer.Populate(jObject.CreateReader(), target);

return target;
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}

你可以这样使用它:

var jsonText = "{a string of json to convert}"
JsonConverter[] conv = new JsonConverter[] { new MessageConverter() };
var jsonResponse = JsonConvert.DeserializeObject<ConversationAPI>(jsonText, conv);

关于c# - 使用 JsonConvert.DeserializeObject 反序列化派生对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19157765/

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