Unity 3D json嵌套使用以及多種類型匹配


我們控制端要發送很多命令給終端設備,其中有速度,方向,開關門,開關燈。。。。我喜歡把有規律的東西放在一起寫!為了我的強迫症!

  

using UnityEngine;
using System.Collections;
using System;
public class Json : MonoBehaviour {
    public JsonType msg = new JsonType();
    public Speed speed = new Speed();

    [Serializable]
    public class JsonType
    {
        public int type;
        public string str; 
    }
    [Serializable]
    public class Speed
    {
        public int id;
        public int speed;
    }
    [Serializable]
    public class Direction
    {
        public int id;
        public int direction;
    }
    void Start()
    {
        msg.type = 1;
        speed.id = 1;
        speed.speed = 100;

        msg.str = JsonUtility.ToJson(speed);  
        string message = JsonUtility.ToJson(msg);
        
        int type = JsonUtility.FromJson<JsonType>(message).type;
        string str = JsonUtility.FromJson<JsonType>(message).str;

        print("message:" + message);
        print("type:" + type);
        print("str:" + str);

        switch (type)
        {
            case 1:
                print("speed:"+JsonUtility.FromJson<Speed>(str).speed);
                break;
            default:
                break;
        }
       
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM