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