下面简单说一下unity使用C#脚本如何解析json数据吧。
一、写解析类,借助于JsonUtility.FromJson
直接给个例子吧
1.json文件testJson.json内容,存储位置/Users/lpp/Downloads/testJson.json
{
"name":"小明",
"age":20,
"interests":["sing","run"]
}
2.c#解析类ModelTest.cs
[System.Serializable]
public class ModelTest
{
public string name;
public int age;
public string[] interests;
}
3.测试脚本
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 () {
}
}
二、使用Newtonsoft插件,无需解析类
网上下一个Newtonsoft.Json.dll,拖到Assets下某个位置,
上面同一个json,不再需要写解析类了,解析方式如下:
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);
}
}
}