由于unity(目前是用unity5.5)目前最高支持.net framework 版本是3.5,所以无法直接通过NuGet导入Newtonsoft.Json来使用。
可以访问GitHub下载相应的支持Unity的Newtonsoft.Json资源包,导入即可使用。(https://github.com/SaladLab/Json.Net.Unity3D/releases)
导入后如下图所示 :
导入后的状态
1.将类(对象)序列化成对应的json语句:
//将Product对象转换为Json字符串
string json = JsonConvert.SerializeObject(product);
2.将json语句反序列化成对应的类(对象)
①此处对应的类是需要根据json语句中的数据来事先定义:
[System.Serializable]
public class CharacterListItem
{
public int Id { get; set; }
public string Name { get; set; }
public int Level { get; set; }
public string Class { get; set; }
public string Sex { get; set; }
}
②然后用JsonConvert.DeserializeObject<>()的方法反序列化成对应的类
如:
//将Json字符串转换为CharacterListItem类对象
Var Object = JsonConvert.DeserializeObject<CharacterListItem>(json);

本文介绍了如何在Unity环境中配置并使用Newtonsoft.Json库进行JSON序列化与反序列化操作。由于Unity仅支持.NET Framework 3.5,因此无法直接通过NuGet安装此库。文章提供了从GitHub获取适用于Unity的Newtonsoft.Json资源包的方法,并展示了如何将其导入Unity项目。此外,还详细解释了两个主要用例:序列化对象为JSON字符串以及将JSON字符串反序列化为对象。

1万+

被折叠的 条评论
为什么被折叠?



