我有一个简单的对象,我的API返回
{
"Code":0,
"Message":"String",
"Data":"Can Be Anything"
}
数据可以是字符串或任何其他对象,如人物,猫,列表等......
我将响应映射到c#,将Data作为Object,假设我将此对象称为“Response”
我想知道在反序列化时是否可行我告知数据类型的类型,并让我们理解并将数据转换为我传递的类型。
会像
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": "aa@aaa.com", "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
转换器会将对象数据转换为Person Data !!!
转换器我尝试了一些没有成功的代码!我尝试了很多代码,我可以从这里得到的结果How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?
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;
}
}
答案 0 :(得分:1)
我认为最好的前进方法是将Code
和Message
的反序列化卸载到JObject
,然后使用JsonConvert
反序列化数据对象。
https://dotnetfiddle.net/bP2Ew6
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
string json = @"
{
""Code"":1,
""Message"":""OK"",
""Data"": {""Name"": ""Patrick"", ""Email"": ""aa@aaa.com"", ""Age"" : 25}
}";
Console.WriteLine(json);
var response=json.ToWrapper<Person>();
Console.WriteLine("Name: "+response.Data.Name);
Console.WriteLine("Email: "+response.Data.Email);
Console.WriteLine("Age: "+response.Data.Age);
}
}
public class Person{
public string Name {get;set;}
public string Email {get;set;}
public int Age {get;set;}
}
public class Response<T>{
public int Code {get;set;}
public string Message {get;set;}
public T Data {get;set;}
}
public static class ResponseExtensions {
public static Response<T> ToWrapper<T>(this string json){
var o=JObject.Parse(json);
var data=JsonConvert.DeserializeObject<T>(o["Data"].ToString());
return new Response<T>{
Code=(int)o["Code"],
Message=(string)o["Message"],
Data=data
};
}
}