U3DC.COM | 优三帝研究院

Menu

Unity中使用Json.Net进行序列化反序列化(二)

使用Json进行序列化的时候,正常情况下,序列化一些基本类型是完全没问题的,但是如果序列化Unity封装的诸如Verctor3等类型,就可能会出错。这时候使用Json.Net的一些配置,即可轻松解决这个问题。以下是一个样例,可以作为参考:

public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; }
public Vector3 Ve { get; set; }
public Dictionary<string, Vector3> StrVector3Dictionary { get; set; }
}
public class UsingJsonDotNetInUnity
{
private void Init()
{
var accountJames = new Account
{
Email = "james@example.com",
Active = true,
CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
Roles = new List<string>
{
"User",
"Admin"
},
Ve = new Vector3(10, 3, 1),
StrVector3Dictionary = new Dictionary<string, Vector3>
{
{"start", new Vector3(0, 0, 1)},
{"end", new Vector3(9, 0, 1)}
}
};

var accountOnion = new Account
{
Email = "onion@example.co.uk",
Active = true,
CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
Roles = new List<string>
{
"User",
"Admin"
},
Ve = new Vector3(0, 3, 1),
StrVector3Dictionary = new Dictionary<string, Vector3>
{
{"vr", new Vector3(0, 0, 1)},
{"pc", new Vector3(9, 9, 1)}
}
};

// 配置
var setting = new JsonSerializerSettings();
setting.Formatting = Formatting.Indented;
setting.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

// 写入
var accountsFromCode = new List<Account> {accountJames, accountOnion};
var json = JsonConvert.SerializeObject(accountsFromCode, setting);
var path = Path.Combine(Application.dataPath, "hi.json");
File.WriteAllText(path, json);

// 读出
var fileContent = File.ReadAllText(path);
var accountsFromFile = JsonConvert.DeserializeObject<List<Account>>(fileContent);
var reSerializedJson = JsonConvert.SerializeObject(accountsFromFile, setting);

print(reSerializedJson);
print("json == reSerializedJson is" + (json == reSerializedJson));
}

前一篇关于接口序列化的:https://www.u3dc.com/archives/3461


博主公众号

打赏
— 于 共写了1659个字
— 文内使用到的标签:

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据