Unity Json转换Sring类型,用于socokect传送消息

需要传送的类: 

 [Serializable]

    public class PlayerInfo
    {
        public Vector3 _Position;
        public Vector3 _Rotion;
        public string _GameObjectName = "";
        public bool _State = false;
        public Vector3 _LeftHandPosition;
        public Vector3 _LeftHandRotion;
        public Vector3 _RightHandPosition;
        public Vector3 _RightHandRotion;

    }


自己写的序列化上面类的方法:

string JsonSeriable(string messageHand, Vector3 position,Vector3 rotion,string TargetName, bool state,Vector3 leftHandPostion, Vector3 leftHandRotion, Vector3 rightHandPostion, Vector3 rightHandRotion)
    {
        PlayerInfo _playerInfo = new PlayerInfo();
        _playerInfo._GameObjectName = TargetName;
        _playerInfo._Position = position;
        _playerInfo._Rotion = rotion;
        _playerInfo._State = state;
        _playerInfo._LeftHandPosition = leftHandPostion;
        _playerInfo._LeftHandRotion = leftHandRotion ;
        _playerInfo._RightHandPosition = rightHandPostion;
        _playerInfo._RightHandRotion = rightHandRotion;
        //得到json 可读性字符串 
        string json = messageHand +"|" + JsonUtility.ToJson(_playerInfo)+"|";
        return json;
    }


得到序列化的字符串,来反序列化:

//message[1]是上面 JsonUtility.ToJson(_playerInfo)后的消息;

PlayerInfo _ClinetPlayerInfo = JsonUtility.FromJson(message[1]) as PlayerInfo;

 JsonUtility.FromJsonOverwrite(JsonUtility.ToJson(message[1]), _ClinetPlayerInfo);     

这样发序列化就好了,信息都存到_ClinetPlayerInfo这里面了


你可能感兴趣的:(unity)