欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Unity 读取解析Json 文件

程序员文章站 2024-01-20 12:39:46
...

Unity 读取Json文件,可以用Unity自带的json解析,也可以用外部的。
Json 引用文件:LitJson.dll 放入Unity项目目录中

使用在线Json工具快速创建一个Json: https://www.sojson.com/

Unity 读取解析Json 文件
然后保存到本地,放入Unity目录中的StreamingAssets文件夹

Unity 读取解析Json 文件
然后将json转成C#实体类
Unity 读取解析Json 文件
Unity 读取解析Json 文件
最后是代码部分

using LitJson;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class JsonTest : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        StreamReader streamreader = new StreamReader(Application.streamingAssetsPath + "/Content.json");
        JsonReader js = new JsonReader(streamreader);//再转换成json数据
        Root r = JsonMapper.ToObject<Root>(js);//读取

        for (int i = 0; i < r.Content.Count; i++)
        {
            Debug.Log("学号:" + r.Content[i].ID + "   " + "名字:" + r.Content[i].name);
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

public class Content
{
    /// <summary>
    /// 
    /// </summary>
    public int ID { get; set; }
    /// <summary>
    /// 
    /// </summary>
    public string name { get; set; }
}

public class Root
{
    /// <summary>
    /// 
    /// </summary>
    public List<Content> Content { get; set; }
}