unity解析json的两种方式

一直比较钟情于json,用来做数据交互,堪称完美!下面简单说一下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 () { }
}

4.输出

unity解析json的两种方式

二、使用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);
}
} }

  输出同样的内容。

 
上一篇:【转】c# 解析JSON的几种办法


下一篇:core dump + LINUX 内核系列博客