美文网首页Unity3d游戏开发
Unity3d 读取JSON数据

Unity3d 读取JSON数据

作者: 王广帅 | 来源:发表于2020-02-16 20:25 被阅读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目录下,如图所示:

    导入Json库

    基本用法

    1. 对象转化为Json格式
       using Newtonsoft.Json;
    
        public static string JsonToString(object value)
        {
             return JsonConvert.SerializeObject(value);
        }
    
    1. Json格式转化为对象
       using Newtonsoft.Json;
    
        public static T JsonToObject<T>(string json)
        {
             return JsonConvert.DeserializeObject<T>(json);
        }
    
    1. 将对象序列化到文件
    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);
    }
    
    1. 反序列化数组
    string json = @"['Starcraft','Halo','Legend of Zelda']";
    
    List<string> videogames = JsonConvert.DeserializeObject<List<string>>(json);
    
    1. 反序列化为字典
    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#!

    求关注,求打赏.png

    相关文章

      网友评论

        本文标题:Unity3d 读取JSON数据

        本文链接:https://www.haomeiwen.com/subject/ctcmfhtx.html