Unity3d 读取JSON数据
2020-02-16 本文已影响0人
王广帅
在做Unity3d游戏开发的时候,需要处理服务器或进配置文件的JSON数据,我使用了LitJson和NewtonsoftJson这两种,在使用Litjson的时候,遇到各种不顺利,这里就不多说了,还是感觉NewtonsoftJson好用,它的特点就是简单,好用。
NewtonsoftJson库导入
本次示例使用的Unity3d版本是2019.3.1f1
,NewtonsoftJson的版本tag是8.0.3,它的github地址是:https://github.com/JamesNK/Newtonsoft.Json/tree/8.0.3
注意,网上很多示例都是导入它的dll文件,这样在unity3d编辑器里面使用是没有问题的,但是如果发布成安卓包就会有异常。所以要把NewtonsoftJson项目中src下面的Newtonsoft.Json中的原文件整个添加到unity3d的Plugins目录下,如图所示:
![](https://img.haomeiwen.com/i3793531/1a8185685f424e1c.png)
基本用法
- 对象转化为Json格式
using Newtonsoft.Json;
public static string JsonToString(object value)
{
return JsonConvert.SerializeObject(value);
}
- Json格式转化为对象
using Newtonsoft.Json;
public static T JsonToObject<T>(string json)
{
return JsonConvert.DeserializeObject<T>(json);
}
- 将对象序列化到文件
Movie movie = new Movie
{
Name = "Bad Boys",
Year = 1995
};
// serialize JSON to a string and then write string to a file
File.WriteAllText(@"c:\movie.json", JsonConvert.SerializeObject(movie));
还有一种方式,直接序列化到文件中:
// serialize JSON directly to a file
using (StreamWriter file = File.CreateText(@"c:\movie.json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, movie);
}
- 反序列化数组
string json = @"['Starcraft','Halo','Legend of Zelda']";
List<string> videogames = JsonConvert.DeserializeObject<List<string>>(json);
- 反序列化为字典
string json = @"{
'href': '/account/login.aspx',
'target': '_blank'
}";
Dictionary<string, string> dic= JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
更多高级用法,可以参考官网介绍:https://www.newtonsoft.com/json/help/html/Samples.htm#!
![](https://img.haomeiwen.com/i3793531/7367ae94d4b72cea.png)