当前位置:   article > 正文

Unity 的Json转换_unity jsonconvert 转换json

unity jsonconvert 转换json

今天讲特别基础但是在混合开发中常用的数据传递,Json格式数据 的序列化和反序列化。我就以我做的3d音乐功能为例 定义: 1.基础类型

  1. public class Communication
  2. {
  3. public long id;
  4. public string data;
  5. public Communication(long id=0, string data=null)
  6. {
  7. this.id = id;
  8. this.data = data;
  9. }
  10. }

2.音乐类型

  1. [Serializable]
  2. public class MusicInfo
  3. {
  4. //localCoverPath:本地缓存的封面图片地址
  5. //netCoverPath:封面图片的网络地址
  6. //name:歌曲名
  7. //author:歌曲作者
  8. //state:歌曲播放状态,0为播放,1为暂停,如果只是单纯操作播放暂停,state之外其他字段可为空
  9. public string localCoverPath;
  10. public string netCoverPath;
  11. public string name;
  12. public string author;
  13. public int state;
  14. }
  1. private static bool TryParse<T>(string json, out T t)
  2. {
  3. try
  4. {
  5. var data = JsonConvert.DeserializeObject<T>(json);
  6. if (data != null)
  7. {
  8. t = data;
  9. return true;
  10. }
  11. }
  12. catch (Exception e)
  13. {
  14. Debug.LogWarning($"TryParse -> json:{json} | e:{e}");
  15. }
  16. t = default;
  17. return false;
  18. }

反序列化

  1. public void SetMusicInfo(string dataJson)
  2. {
  3. if (!TryParse<Communication>(dataJson, out var communication))
  4. {
  5. var errMsg = "SetMusicInfo: Invalid json -> " + dataJson;
  6. Debug.Log(errMsg);
  7. CallBackToAndroid.RequestCallBack(false, -1, errMsg);
  8. return;
  9. }
  10. if (!TryParse<MusicInfo>(communication.data, out var musicInfo))
  11. {
  12. var errMsg = "SetMusicInfo: Invalid musicInfo -> " + dataJson;
  13. Debug.Log(errMsg);
  14. CallBackToAndroid.RequestCallBack(false, communication.id, errMsg);
  15. return;
  16. }
  17. var musicSoundController = FindObjectOfType<MusicSoundController>();
  18. if (musicSoundController == null)
  19. {
  20. var errMsg = "SetMusicInfo: musicSoundController not init -> " + dataJson;
  21. Debug.Log(errMsg);
  22. CallBackToAndroid.RequestCallBack(false, communication.id, errMsg);
  23. return;
  24. }
  25. Debug.Log("SetMusicInfo -> " + dataJson);
  26. musicSoundController.UpdateMusicInfo(musicInfo);
  27. CallBackToAndroid.RequestCallBack(true, communication.id, "");
  28. }

序列化:

  1. var info = new MusicInfo()
  2. {
  3. author = "",
  4. localCoverPath = "",
  5. name = "",
  6. netCoverPath = ""
  7. };
  8. var musicCommunication = new Communication()
  9. {
  10. id= 0,
  11. data = JsonUtility.ToJson(info)
  12. };
  13. JsonUtility.ToJson(musicCommunication);

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号