JsonTool.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. //************************************************************************
  2. // https://github.com/yuzhengyang
  3. // author: yuzhengyang
  4. // date: 2017.3.29 - 2017.8.24
  5. // desc: Json转换工具类(需要Newtonsoft.Json支持)
  6. // Copyright (c) yuzhengyang. All rights reserved.
  7. //************************************************************************
  8. using Azylee.Core.IOUtils.TxtUtils;
  9. using Newtonsoft.Json;
  10. using System;
  11. namespace Azylee.Core.Plus.DataUtils.JsonUtils
  12. {
  13. public class JsonTool
  14. {
  15. public static string ToStr(object value)
  16. {
  17. return JsonConvert.SerializeObject(value);
  18. }
  19. public static object ToObjFromStr(string str)
  20. {
  21. string json = str;
  22. if (!string.IsNullOrWhiteSpace(json))
  23. {
  24. try { return JsonConvert.DeserializeObject(json); } catch (Exception e) { }
  25. }
  26. return null;
  27. }
  28. public static T ToObjFromStr<T>(string str)
  29. {
  30. string json = str;
  31. if (!string.IsNullOrWhiteSpace(json))
  32. {
  33. try { return JsonConvert.DeserializeObject<T>(json); } catch (Exception e) { }
  34. }
  35. return default(T);
  36. }
  37. public static T ToObjFromFile<T>(string file)
  38. {
  39. string json = TxtTool.Read(file);
  40. if (!string.IsNullOrWhiteSpace(json))
  41. {
  42. try { return JsonConvert.DeserializeObject<T>(json); } catch (Exception e) { }
  43. }
  44. return default(T);
  45. }
  46. }
  47. }