JsonTool.cs 993 B

123456789101112131415161718192021222324252627282930
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace KdanCommon.Helpers
  8. {
  9. public static class JsonTool
  10. {
  11. /// <summary>
  12. /// Deserialize json to target class
  13. /// when jsonStr deserializes failed, put default value in there
  14. /// </summary>
  15. public static T DeserializeJSON<T>(string jsonStr)
  16. {
  17. T response = default(T);
  18. response = JsonConvert.DeserializeObject<T>(jsonStr, new JsonSerializerSettings()
  19. {
  20. Error = (sender, errorEventArgs) =>
  21. {
  22. System.Diagnostics.Debug.WriteLine(String.Format("error happen in {0} : {1}", errorEventArgs.CurrentObject.GetType().Name, errorEventArgs.ErrorContext.Error.Message));
  23. errorEventArgs.ErrorContext.Handled = true;
  24. }
  25. });
  26. return response;
  27. }
  28. }
  29. }