JsonTool.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. //############################################################
  2. // https://github.com/yuzhengyang
  3. // author:yuzhengyang
  4. //############################################################
  5. using Newtonsoft.Json;
  6. using System;
  7. using Y.Utils.IOUtils.TxtUtils;
  8. namespace Y.Utils.DataUtils.JsonUtils
  9. {
  10. public class JsonTool
  11. {
  12. public static string ToStr(object value)
  13. {
  14. return JsonConvert.SerializeObject(value);
  15. }
  16. public static object ToObjFromStr(string str)
  17. {
  18. string json = str;
  19. if (!string.IsNullOrWhiteSpace(json))
  20. {
  21. try { return JsonConvert.DeserializeObject(json); } catch (Exception e) { }
  22. }
  23. return null;
  24. }
  25. public static T ToObjFromStr<T>(string str)
  26. {
  27. string json = str;
  28. if (!string.IsNullOrWhiteSpace(json))
  29. {
  30. try { return JsonConvert.DeserializeObject<T>(json); } catch (Exception e) { }
  31. }
  32. return default(T);
  33. }
  34. public static T ToObjFromFile<T>(string file)
  35. {
  36. string json = TxtTool.Read(file);
  37. if (!string.IsNullOrWhiteSpace(json))
  38. {
  39. try { return JsonConvert.DeserializeObject<T>(json); } catch (Exception e) { }
  40. }
  41. return default(T);
  42. }
  43. }
  44. }