C#Newtonsoft Json转换器将Generic反向串行化为具体的混凝土

问题描述 投票:0回答:1

我有一个简单的对象,我的API返回

{
"Code":0,
"Message":"String",
"Data":"Can Be Anything"
}

数据可以是字符串或任何其他对象,如人物,猫,列表等......

我将响应映射到c#将Data作为Object,让我说我称这个对象为“Response”

我想知道,当我反序列化时是否可能我告知数据类型的类型并使得一个converert理解并将数据转换为我通过的类型。

会是这样的

public static Response ToWrapper<T>(this string json)
{
    return JsonConvert.DeserializeObject<Response>(json, new Converter<T>());
}

在这个例子中,我会说Data是一个名为Person的虚拟类,其中包含道具字符串Name,字符串Email和int Age,因此响应将是

string json = "
{
   "Code":1,
   "Message":"OK",
   "Data": {"Name": "Patrick", "Email": "[email protected]", "Age" : 25}
}"

所以在我的代码的某些方面我会

var ResponseWrapper = json.ToWrapper<Person>();

string personName = ResponseWrapper.Data.Name;  
string personEmail = ResponseWrapper.Data.Email;
int personAge = ResponseWrapper.Data.Age; //<----- NO CAST NEEDED

转换器会将对象数据转换为人员数据!

转换器我尝试了一些代码没有成功!我尝试了很多代码,我可以得到的关闭是来自这里qazxsw poi

How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?
c# json generics json.net
1个回答
1
投票

我认为最好的前进方法是使用public class PersonConverter<T> : JsonCreationConverter<T> { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } protected override T Create(Type objectType, JObject jObject) { T obj = Activator.CreateInstance<T>(); if (FieldExists("Data", jObject)) { return obj; } else return obj; } 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 true; // typeof(T).IsAssignableFrom(objectType); } public override bool CanWrite { get { return false; } } 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; } } Code的反序列化卸载到Message,然后使用JObject反序列化数据对象。

JsonConvert

https://dotnetfiddle.net/bP2Ew6
© www.soinside.com 2019 - 2024. All rights reserved.