一、Json
这里使用的是Json的一个开源项目LitJson
1.官网下载地址:http://www.json.org/
下载好的dll文件放在Plugins文件夹中
- 注意JSON的格式,可在线编辑并检查格式是否有问题https://www.bejson.com/jsoneditoronline/,检查无误后保存并放在Resources文件夹中
{
"Name": "yusong",
"Age": 26,
"Birthday": "1986-11-21",
"Thumbnail": [
{
"Url": "http://xuanyusong.com",
"Height": 256,
"Width": "200"
},
{
"Url": "http://baidu.com",
"Height": 1024,
"Width": "500"
}
]
}
3.解析JSON字符串显示字典键值,记得引用dll文件
using LitJson;//记得引用dll文件
public void ParseJson()
{
//加载文本 TextAsset
TextAsset itemText = Resources.Load<TextAsset>("Items");
string itemsJson = itemText.text;
//这里是解析,包括整形与字符串
JsonData jd = JsonMapper.ToObject(itemsJson);
Debug.Log("name = " + (string)jd["Name"]);
Debug.Log("Age = " + (int)jd["Age"]);
Debug.Log("Birthday = " + (string)jd["Birthday"]);
JsonData jdItems = jd["Thumbnail"];
for (int i = 0; i < jdItems.Count; i++)
{
Debug.Log("URL = " + jdItems[i]["Url"]);
Debug.Log("Height = " + (int)jdItems[i]["Height"]);
Debug.Log("Width = " + jdItems[i]["Width"]);
}
}
二、Protobuf-net
下载地址:https://code.google.com/archive/p/protobuf-net/downloads
提取出 .dll文件:压缩包–> Full(所有平台) –> unity –> protobuf-net.dll,同样放在Plugins文件夹中。
网络通信时的传输流程:①一般是按照定义的.proto数据格式,打包成对应的数据对象(我们这儿的user类),然后用protobuf.encode(编码) 序列化为byte[], 再encrypt(加密),还是byte[]。然后传输 ②.接到后decrypt(解密) 然后 protobuf.decode(解码)
- 创建数据类 User
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ProtoBuf;
[ProtoContract]//声明为protobuf的数据来传输
public class User
{
//序列化必须制定一个tag 便于二进制中识别
[ProtoMember(1)]
public int id = 3;
[ProtoMember(2)]
public string userName = "monkey";
[ProtoMember(3)]
public string password = "123456";
[ProtoMember(4)]
public int level = 10;
[ProtoMember(5)]
public userType _userType = userType.master;
public enum userType
{
master,
warrior
}
}
- 使用protobuf进行数据的序列化和反序列化
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ProtoBuf;
using System.IO;
public class TestProtobuf : MonoBehaviour
{
void Start ()
{
this.Serialize();
}
//序列化
void Serialize()
{
User user = new User();
FileStream fs = File.Create(Application.dataPath + "/user.bin"); //创建的数据流 生成 user.bin 文件
Debug.Log(Application.dataPath + "/user.bin");
Serializer.Serialize<User>(fs, user);
fs.Close();
////创建的数据流 自动关闭
//using (var fs = File.Create(Application.dataPath + "/user.bin"))
//{
// Serializer.Serialize<User>(fs, user);
//}
}
//反序列化
void Deserialize()
{
User user = null;
using (var fs = File.OpenRead(Application.dataPath + "/user.bin"))
{
user = Serializer.Deserialize<User>(fs);
}
print(user.id);
print(user.userName);
}
}