如何使用Newtonsoft.NET将JSON数组转化成C#匿名类集合?
使用Newtonsoft.NET将JSON数组转化成C#匿名类集合
var url = "";
var patientMsg = await httpClient.
GetStringAsync($"{url}?BingQuDM=1");
//1.转义后的Json 字符串
patientMsg = "{\"Rows\":[{\"DeptCode\":\"1001\",\"BedNum\":\"001\",\"PatientName\":\"卞肇琪\",\"PatientSex\":\"女\",\"PatientAge\":22,\"NursingGrade\":\"三级护理\",\"DietAndRisk\":\"流性食物/留置导尿/记尿量\",\"TempBaseId\":null,\"TempStickId\":null,\"HBRId\":null,\"InfusionId\":null,\"DropRate\":null,\"Temperature\":null,\"HeartRate\":null}]}";
//2.按照接口请求过来的Json字符串格式来声明的一个匿名对象
var patientAnonymous = new { Rows = new[] {
new { BingRenZYID = "", BingRenID = "",
ChuangWeiHao = "", XingMing = "", XingBie = "",
NianLing = "", HuLiDJ = "", RuYuanSJ = "",
ZhuYuanCS = "", ChuYuanSJ = "",
Description="", MattressNo="" } } };
//3.利用DeserializeAnonymousType方法
//把Json字符串转成匿名类型的集合
var patientList = JsonConvert.DeserializeAnonymousType(patientMsg,
patientAnonymous).Rows.ToList();
//4.可以不看,有需要可以看 把匿名对象的集合通过反射转为dynamic 的集合
// 是因为下面我有需要对这个匿名对象集合的子项进行赋值的操作,
//匿名对象的属性本身不支持赋值的操作,所以把它转为dynamic类型的
List<dynamic> set = new List<dynamic>();
foreach (var p in patientList)
{
var pros= p.GetType().GetProperties(BindingFlags.Public
| BindingFlags.Instance);
var d = new ExpandoObject();
foreach (var ps in pros)
{
//eg:d.BingRenID = ps.BingRenID;
(d as IDictionary<string, dynamic>)
.Add(ps.Name, ps.GetValue(p, null));
}
set.Add(d);
}
//第二种 直接转为dynamic类型的 因为是动态类型 所以vs 没有智能提示
string hj = "{\"Rows\":[{\"DeptCode\":\"1001\",\"BedNum\":\"001\",\"PatientName\":\"卞肇琪\",\"PatientSex\":\"女\",\"PatientAge\":22,\"NursingGrade\":\"三级护理\",\"DietAndRisk\":\"流性食物/留置导尿/记尿量\",\"TempBaseId\":null,\"TempStickId\":null,\"HBRId\":null,\"InfusionId\":null,\"DropRate\":null,\"Temperature\":null,\"HeartRate\":null},{\"DeptCode\":\"1001\",\"BedNum\":\"001\",\"PatientName\":\"卞肇琪\",\"PatientSex\":\"女\",\"PatientAge\":22,\"NursingGrade\":\"三级护理\",\"DietAndRisk\":\"流性食物/留置导尿/记尿量\",\"TempBaseId\":null,\"TempStickId\":null,\"HBRId\":null,\"InfusionId\":null,\"DropRate\":null,\"Temperature\":null,\"HeartRate\":null}]}";
dynamic json = Newtonsoft.Json.Linq.JToken.Parse(hj) as dynamic;
foreach (var item in json)
{
Console.WriteLine($"count:{item.PatientName},no:{item.PatientAge}");
}