JsonManager.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using LitJson;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using UnityEngine;
  6. public class JsonManager : MonoBehaviour
  7. {
  8. public const string TAG = "JsonManager";
  9. private static JsonManager m_Instance;
  10. public static JsonManager Instance
  11. {
  12. get
  13. {
  14. if (null == JsonManager.m_Instance)
  15. {
  16. GameObject gameObject = GameObject.Find("JsonManager");
  17. if (null == gameObject)
  18. {
  19. gameObject = new GameObject("JsonManager");
  20. gameObject.transform.localPosition = new Vector3(0f, 0f, 0f);
  21. DontDestroyOnLoad(gameObject);
  22. }
  23. m_Instance = gameObject.AddComponent<JsonManager>();
  24. }
  25. return m_Instance;
  26. }
  27. }
  28. //public UdpClient UdpClient
  29. //{
  30. // get
  31. // {
  32. // if (null == m_UdpClient)
  33. // {
  34. // m_UdpClient = GameObject.Find("Socket").GetComponent<UdpClient>();
  35. // }
  36. // return m_UdpClient;
  37. // }
  38. // set { m_UdpClient = value; }
  39. //}
  40. /// <summary>
  41. /// 解析从服务器接收到的数据
  42. /// 根据解析的数据有多个泛型解析方法
  43. /// </summary>
  44. /// <param name="jsonData">要解析的数据</param>
  45. /// <returns>是否解析成功</returns>
  46. public bool AnalysisJson(string jsonData)
  47. {
  48. if (jsonData == "" || jsonData == "Message")
  49. {
  50. Debug.LogError("未接受到json 数据");
  51. return false;
  52. }
  53. try
  54. {
  55. //根据泛型进行解析
  56. QuestionInfor infor = JsonMapper.ToObject<QuestionInfor>(jsonData);
  57. return true;
  58. }
  59. catch (Exception)
  60. {
  61. Debug.LogError("Json 传入格式不正确 无法解析");
  62. return false;
  63. }
  64. }
  65. }