最近用Json来进行一些序列化和反序列化的操作,从中也学到了很多以前没有接触过的知识,昨天经理问了我一个问题,如果给你一个序列化好的Json,你将他反序列化出来以后如何得知这个Json的对象类型,这刚开始的时候确实没想到该怎么做,一点头绪都没有,想着强制转换但是因为不知道Json的对象类型,总不能一个个对象类型都试过去,后来经理教了我一个办法,因为C#的类型都是强类型,他最大的特点就是能自己说明自己,这样的话只需要在序列化对象类里面多写一个属性TypeFullName来存储该类的类型,然后在反序列化的时候将这个值显示出来,就能知道这条Json是什么类型的对象转化过来的了,下面上代码。
首先是对象类,这里我就随便定义了一个对象类:
namespace ConsoleApplication1
{
public class DemoDto
{
public DateTime AddTime { get; set; }
public string Id { get; set; }
public int Price { get; set; }
public string TypeFullName
{
get
{
if (string.IsNullOrEmpty(typeFullName))
{
typeFullName = this.GetType().FullName;//此处获得的值为ConsoleApplication1.DemoDto
}
return typeFullName;
}
set { typeFullName = value; }
}
}
}
接下来就是GetJsonObject(string Json)方法了,这个方法主要是实现Json的反序列化,先获取typeFullName字段的值,然后将该值作为一个Type再对Json进行一次反序列化,然后返回一个object: public static object GetJsonObject(string Json)
{
object o = JsonConvert.DeserializeObject(Json);
Console.WriteLine(o.GetType().ToString());
if (o is JObject)
{
string typeName =(string) (o as JObject).Property("TypeFullName").Value;
Type t = Type.GetType(typeName);
o=JsonConvert.DeserializeObject(Json,t);
Console.WriteLine(o);
return o;
}
return null;
}
然后就是因为不知道是什么类型,所以接下来的方法使用到了泛型的定义:
public static T GetGenericOBject<T>(string Json)
{
return (T)GetJsonObject(Json);//返回一个泛型指定的类型
}