JsonManage.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using LitJson;
  2. using Newtonsoft.Json;
  3. using Newtonsoft.Json.Linq;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using UnityEngine;
  7. public class JsonManage : MonoSingleton<JsonManage>
  8. {
  9. /// <summary>
  10. /// 通用解析Jsong 解析为任意类 ,请求成功返回 T ,失败返回null/0
  11. /// </summary>
  12. /// <typeparam name="T"> 需要解析的类型 </typeparam>
  13. /// <param name="message"></param>
  14. /// <returns></returns>
  15. public T ToJsonClass<T>(string message)
  16. {
  17. Debug.Log(message);
  18. JObject data = null;
  19. var isSucess = CheckMessage(message, out data);
  20. if (!isSucess)
  21. {
  22. return default(T);
  23. }
  24. message = data["data"].ToString();
  25. if (string.IsNullOrWhiteSpace(message) || message == "[]" || message == "{\r\n \"list\": []\r\n}")
  26. {
  27. return default(T);
  28. }
  29. T jsonClass = JsonMapper.ToObject<T>(message);
  30. return jsonClass;
  31. }
  32. /// <summary>
  33. /// 检查获取的信息是否正确
  34. /// </summary>
  35. /// <param name="message"></param>
  36. /// <param name="data"></param>
  37. /// <returns></returns>
  38. public bool CheckMessage(string message, out JObject data)
  39. {
  40. bool isSucess = true;
  41. data = JsonConvert.DeserializeObject<JObject>(message);
  42. if (data["code"].ToString() != "200")
  43. {
  44. isSucess = false;
  45. data = null;
  46. Debug.LogError("Json解析失败 " + message);
  47. }
  48. return isSucess;
  49. }
  50. }