一直比较钟情于json,用来做数据交互,堪称完美!下面简单说一下unity使用C#脚本如何解析json数据吧。
一、写解析类,借助于JsonUtility.FromJson
直接给个例子吧
1.json文件testJson.json内容,存储位置/Users/lpp/Downloads/testJson.json
1 2 3 4 5 | { "name" : "小明" , "age" :20, "interests" :[ "sing" , "run" ] } |
2.c#解析类ModelTest.cs
1 2 3 4 5 6 7 | [System.Serializable] public class ModelTest { public string name; public int age; public string [] interests; } |
3.测试脚本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | using UnityEngine; using System.IO; using System.Text; public class JsonTest : MonoBehaviour { // Use this for initialization void Start () { string jsonTest = File.ReadAllText( "/Users/lpp/Downloads/testJson.json" , Encoding.UTF8); ModelTest obj = JsonUtility.FromJson<ModelTest>(jsonTest); Debug.Log(obj.name); Debug.Log(obj.age); foreach ( var inter in obj.interests) { Debug.Log(inter); } } // Update is called once per frame void Update () { } } |
4.输出
![](https://i-blog.csdnimg.cn/blog_migrate/a8a3144ca022d54420b4a08367c2a929.png)
二、使用Newtonsoft插件,无需解析类
网上下一个Newtonsoft.Json.dll,拖到Assets下某个位置,
上面同一个json,不再需要写解析类了,解析方式如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | using UnityEngine; using System.IO; using System.Text; using Newtonsoft.Json.Linq; public class JsonTest : MonoBehaviour { // Use this for initialization void Start () { string json = File.ReadAllText( "/Users/lpp/Downloads/testJson.json" , Encoding.UTF8); JObject obj = JObject.Parse(json); Debug.Log(obj[ "name" ].ToString()); Debug.Log(obj[ "age" ].ToString()); JArray ints = (JArray)obj[ "interests" ]; foreach ( var inter in ints) { Debug.Log(inter); } } } |
输出同样的内容。