JsonManager.cs 1.9 KB

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