C# 将任意对象快速转换为Json
2021-02-20 08:17
阅读:698
由于最近项目里面Model类特别多,而我需要编写所有数据交互的接口,传输的格式是json,以前都是通过循环List
////// 转换T为json /// /// 类型 /// 对象 ///json private string ConvertToJson(T model) { //获取属性集合 PropertyInfo[] properties = model.GetType().GetProperties(); StringBuilder sb = new StringBuilder(); sb.Append("{");
//遍历属性集合 for (int i = 0, len = properties.Length; i ) {
if(0!=i)sb.Append(","); sb.AppendFormat("\"{0}\":\"{1}\"", properties[i].Name.ToLower(),//属性名作为 键 properties[i].GetValue(model, null).ToString());//属性值作为 值
} sb.Append("}"); return sb.ToString(); }
通过泛型可以接收任意自定义类型进行操作;
完成了这个之后突然我又发现还是要循环很多List
////// 转换List 为json /// /// /// /// private string ConvertToJson (List models) { StringBuilder sb = new StringBuilder(); for (int i = 0, len = models.Count; i ) { if (0 != i) sb.Append(","); sb.Append(ConvertToJson(models[i])); } return sb.ToString(); } /// /// 转换T为json /// /// /// /// private string ConvertToJson (T model) { //获取属性集合 PropertyInfo[] properties = model.GetType().GetProperties(); StringBuilder sb = new StringBuilder(); sb.Append("{");//遍历属性集合 for (int i = 0, len = properties.Length; i ) {
if(0!=i)sb.Append(","); sb.AppendFormat("\"{0}\":\"{1}\"", properties[i].Name.ToLower(),//属性名作为 键 properties[i].GetValue(model, null).ToString());//属性值作为 值
} sb.Append("}"); return sb.ToString(); }
至此完毕,代码中组织json格式效率方面还望有大神提出宝贵建议!
评论
亲,登录后才可以留言!