JsonUtil.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System.Collections.Generic;
  2. using Tea;
  3. using Newtonsoft.Json;
  4. namespace Alipay.EasySDK.Kernel.Util
  5. {
  6. /// <summary>
  7. /// JSON工具类
  8. /// </summary>
  9. public class JsonUtil
  10. {
  11. /// <summary>
  12. /// 将字典集合转换为Json字符串,转换过程中对于TeaModel,使用标注的字段名称而不是字段的变量名
  13. /// </summary>
  14. /// <param name="input">字典集合</param>
  15. /// <returns>Json字符串</returns>
  16. public static string ToJsonString(IDictionary<string, object> input)
  17. {
  18. IDictionary<string, object> result = new Dictionary<string, object>();
  19. foreach (var pair in input)
  20. {
  21. if (pair.Value is TeaModel)
  22. {
  23. result.Add(pair.Key, GetTeaModelMap((TeaModel)pair.Value));
  24. }
  25. else
  26. {
  27. result.Add(pair.Key, pair.Value);
  28. }
  29. }
  30. return JsonConvert.SerializeObject(result);
  31. }
  32. private static IDictionary<string, object> GetTeaModelMap(TeaModel teaModel)
  33. {
  34. IDictionary<string, object> result = new Dictionary<string, object>();
  35. IDictionary<string, object> teaModelMap = teaModel.ToMap();
  36. foreach (var pair in teaModelMap)
  37. {
  38. if (pair.Value is TeaModel)
  39. {
  40. result.Add(pair.Key, GetTeaModelMap((TeaModel)pair.Value));
  41. }
  42. else
  43. {
  44. result.Add(pair.Key, pair.Value);
  45. }
  46. }
  47. return result;
  48. }
  49. }
  50. }