1.第一种unity自带解析的API JsonUtility 读取Json 不需要dll文件
2.第二种 Newtonsoft.Json dll解析json 读取json
json格式如下
{
"name": [
{
"age": 28,
"sex": "不男不女"
},
{
"age": 7,
"sex": "东方不败"
},
{
"age": 20,
"sex": "男"
},
{
"age": 15,
"sex": "女"
}
]
}
Json文件我是保存在StreamingAssets 下的 textJson.json
c#脚本如下
using Newtonsoft.Json.Linq;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using System;
using Newtonsoft.Json;
[Serializable] //序列化
public class AA
{
public BB[] name;
}
[Serializable] //序列化
public class BB
{
public int age;
public string sex;
}
public class Parsing_json : MonoBehaviour
{
public string jsonpath = Application.streamingAssetsPath + "/textJson.json";
// Start is called before the first frame update
void Start()
{
#region 第一种unity自带解析的API JsonUtility 读取Json
//string json = File.ReadAllText(Application.streamingAssetsPath + "/textJson.json");
//AA aa = JsonUtility.FromJson<AA>(json);
//Debug.Log("年龄" + aa.name[0].age + "性别" + aa.name[0].sex);
//Debug.Log("年龄" + aa.name[1].age + "性别" + aa.name[1].sex);
//Debug.Log("年龄" + aa.name[2].age + "性别" + aa.name[2].sex);
//Debug.Log("年龄" + aa.name[3].age + "性别" + aa.name[3].sex);
#endregion
#region 第二种 Newtonsoft.Json dll解析json 读取json
//string json = File.ReadAllText(Application.streamingAssetsPath + "/textJson.json");
//AA obj = JsonConvert.DeserializeObject<AA>(json);
//Debug.Log("年龄: " + obj.name[0].age + "性别: " + obj.name[0].sex);
//Debug.Log("年龄: " + obj.name[1].age + "性别: " + obj.name[1].sex);
#endregion
#region 创建json 保存到json文件
//// 创建Json
//BB p1 = new BB();
//p1.sex = "不男不女";
//p1.age = 28;
//string json = JsonUtility.ToJson(p1);
//BB p2 = new BB();
//p2.sex = "东方不败";
//p2.age = 7;
//BB[] ps = new BB[] { p1, p2 };
//AA persons = new AA();
//persons.name = ps;
//json = JsonUtility.ToJson(persons);
//if (!System.IO.File.Exists (jsonpath))
//{
// File.CreateText(jsonpath).Dispose();
//}
//File.WriteAllText(jsonpath, json, System.Text.Encoding.UTF8);
#endregion
//解析Json
string jso = File.ReadAllText(jsonpath);
AA obj = JsonUtility.FromJson<AA>(jso);
foreach (var item in obj.name)
{
Debug.Log("年龄: " + item.age + "性别: " + item.sex);
}
}
}
打印出来如下