JsonTool.cs 1.2 KB

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