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;
        }
       
    }
}

posted @ 2017-01-05 11:03  WenanLee  阅读(2147)  评论(0编辑  收藏  举报