JsonTool.cs 1.3 KB

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