C#对象转字典(object to dictionary)
案例背景
最近再做http请求传递参数的时候,服务端服务采用java进行编写,经常遇到不能识别json对象的问题,只能使用form传参的方式进行key,value这种结构进行参数传递,由于前期项目都用的是对象传参,需要对Body内容进行重新组织业务代码。现就将实现的细节进行分享,方便后续遇到同类场景快速找到解决方案。
核心代码
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Reflection; namespace Common { /// <summary> /// 对象装字典帮助类 /// </summary> public static class ModelToDictionaryHelper { /// <summary> /// 第一种通过反射进行转换 /// </summary> /// <typeparam name="T">要转换的类型</typeparam> /// <param name="obj">对象</param> /// <returns></returns> public static Dictionary<string, string> ModelToDic<T>(this T obj) where T:class { Dictionary<string, string> map = new Dictionary<string, string>(); if (obj==null) { return map; } Type t = obj.GetType(); PropertyInfo[] PropertyList = t.GetProperties(); foreach (var item in PropertyList) { string name = item.Name; object value = item.GetValue(obj, null); if (value != null) { map.Add(name, value.ToString()); } else { map.Add(name, ""); } } return map; } /// <summary> /// 借助JsonConvert快速实现转换 /// </summary> /// <typeparam name="T">要转换的类型</typeparam> /// <param name="obj">对象</param> /// <returns></returns> public static Dictionary<string, string> ModelToDic2<T>(this T obj) where T : class { Dictionary<string, string> map = new Dictionary<string, string>(); if (obj == null) { return map; } var objstr = JsonConvert.SerializeObject(obj); //string(json) 转 Dictionary map = JsonConvert.DeserializeObject<Dictionary<string, string>>(objstr); return map; } } }
调用方式比较简单,代码如下:
using Common; using System; namespace ConsoleApp4 { class Program { static void Main(string[] args) { Test1 t1 = new Test1(); t1.Name = "张三"; t1.Id = "10001"; var res1 = t1.ModelToDic(); foreach (var item in res1.Keys) { Console.WriteLine(item+"-->"+res1[item]); } Console.ReadLine(); } } class Test1 { public string Id { get; set; } public string Name { get; set; } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?