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; }
    }
}


posted @ 2022-12-03 09:09  星火燎猿*  阅读(1286)  评论(0)    收藏  举报