举个栗子,代码及注释如下
class Program
{
static void Main(string[] args)
{
// 反射示例
string strjson = "[{\"name\":\"deas\",\"str\":\"male\",\"age\":15,\"bol\":true,\"id\":\"49f6eeb9-6fe9-487f-80c0-2ef1946ce1c3\",\"dt\":\"2020-12-09T11:13:42.8016838+08:00\",\"ffr\":{\"xxj\":\"120\",\"bolxxj\":\"true\"}},{\"name\":\"qeer\",\"str\":\"uyiu\",\"age\":18,\"bol\":false,\"id\":\"cef445cc-ba64-423e-b8a8-2d99f53eaf23\",\"dt\":\"2020-12-09T11:13:42.8056737+08:00\",\"ffr\":{\"xxj\":\"330\",\"bolxxj\":\"false\"}},{\"name\":\"zcvc\",\"str\":\"nbbn\",\"age\":25,\"bol\":true,\"id\":\"751852e7-1d12-44c6-a1c8-0a23263db111\",\"dt\":\"2020-12-09T11:13:42.8056737+08:00\",\"ffr\":{\"xxj\":\"550\",\"bolxxj\":\"true\"}},{\"name\":\"efvv\",\"str\":\"tynm\",\"age\":26,\"bol\":false,\"id\":\"083678c5-4c36-48f2-ba2a-778aaacc433b\",\"dt\":\"2020-12-09T11:13:42.8056737+08:00\",\"ffr\":{\"xxj\":\"670\",\"bolxxj\":\"false\"}}]";
List<Cler> clersList = JsonConvert.DeserializeObject<List<Cler>>(strjson);// 序列化JSON字符串
foreach (Cler cl in clersList)// by 每个对象Cler循环
{
Cler cler = new Cler(cl.name, cl.str, cl.age, cl.bol, cl.id, cl.dt, cl.ffr);// 实例化 调用构造函数为变量赋值
Type tcler = cler.GetType();// 获取当前实例的Type
PropertyInfo[] pi_cler = tcler.GetProperties();// 取得public修饰的对象属性数组(就是有很多很多对象,每个对象为一个元素)
foreach (PropertyInfo pi in pi_cler)// 循环取得每个元素的Type属性
{
Console.WriteLine();
Console.WriteLine(pi.PropertyType.Name);// 字段类型 String/Int32/Boolean/Guid/DateTime/FFR
Console.WriteLine(pi.Name);// 对象名
Console.WriteLine(pi.GetValue(cler));// 对象的值
if (pi.PropertyType.Name == "FFR")
{
string ffrstr = JsonConvert.SerializeObject(pi.GetValue(cler));// 将FFR中的对象转换为JSON字符串
FFR ffrjson = JsonConvert.DeserializeObject<FFR>(ffrstr);// 再将JSON序列化为FFR对象,这样就将Object对象转换为了FFR对象(拆箱操作)
Console.WriteLine(ffrjson.xxj);// 取得FFR.xxj的值
Console.WriteLine(ffrjson.bolxxj);//FFR.bolxxj的值
}
Console.WriteLine();
}
}
Console.ReadKey();
}
static string FunTtu(string str)
{
Console.WriteLine("线程ID:" + Thread.CurrentThread.ManagedThreadId.ToString());
return "FunTtu-" + str;
}
}
class Cler
{
public string name { get; set; }
public string str { get; set; }
public int age { get; set; }
public bool bol { get; set; }
public Guid id { get; set; }
public DateTime dt { get; set; }
public FFR ffr { get; set; }
public Cler(string str_name, string str_str, int str_age, bool str_bol, Guid str_id, DateTime str_dt, FFR str_ffr)
{
name = str_name;
str = str_str;
age = str_age;
bol = str_bol;
id = str_id;
dt = str_dt;
ffr = str_ffr;
}
}
class FFR
{
public int xxj { get; set; }
public bool bolxxj { get; set; }
}