unity Json

本文介绍在Unity中如何使用LitJson第三方库来处理JSON数据,包括字符串到JSON对象的转换、对象到JSON字符串的转换、写入并记录JSON数据、将JSON数据写入文件及从JSON文件读取数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

//本文主要介绍在unity中如何处理json数据
//LitJson是处理JSON的第三方库,需要下载导入
//可直接右键Assets,Import New Asset导入LitJson
using UnityEngine;
using System.Collections;
using LitJson;
using System.IO;
using System.Text;

public class JsonDemo : MonoBehaviour
{
    public TextAsset json;
    public string filePath;
    public string fileName;
    void Awake()
    {
        filePath = Application.dataPath + "/Resources/TextFile";
        fileName = filePath + "/File.json";
        //StringToJson();
        //ObjectToJson();
        //WriteJsonAndLog();
        //writeJsonToFile(filePath,fileName);
        //ReadJsonFromJson();
    }

    public void StringToJson()
    {
        //@ 换行
        string str = @"{'name':'hello','age':16,'items':
[{'height':100,'width':'20'},{'height':'30','width':'40'}]}";

        JsonData jd = JsonMapper.ToObject(str);
        Debug.Log("name:" + (string)jd["name"]);
        Debug.Log("age:" + (int)jd["age"]);

        JsonData jdItems = jd["items"];
        for (int i = 0; i < jdItems.Count; i++)
        {
            Debug.Log("height" + jdItems[i]["height"]);
            Debug.Log("width" + jdItems[i]["width"]);
        }

    }

    public void ObjectToJson()
    {
        Person person = new Person();
        person.age = 10;
        person.name = "caicai";

        string strjson = JsonMapper.ToJson(person);
        Debug.Log(strjson);
        JsonData jd = JsonMapper.ToObject(strjson);
        Debug.Log("name" + jd["name"]);
        Debug.Log("age" + jd["age"]);
    }


    public void WriteJsonAndLog()
    {
        StringBuilder strB = new StringBuilder();
        JsonWriter jsWrite = new JsonWriter(strB);
        jsWrite.WriteObjectStart();
        jsWrite.WritePropertyName("name");
        jsWrite.Write("caicai");
        jsWrite.WritePropertyName("list");
        jsWrite.WriteArrayStart();
        jsWrite.WriteObjectStart();
        jsWrite.WritePropertyName("name");
        jsWrite.Write("huahua");
        jsWrite.WriteObjectEnd();
        jsWrite.WriteObjectStart();
        jsWrite.WritePropertyName("name");
        jsWrite.Write("huanghuang");
        jsWrite.WriteObjectEnd();
        jsWrite.WriteArrayEnd();
        jsWrite.WriteObjectEnd();
        Debug.Log(strB);
        JsonData jd = JsonMapper.ToObject(strB.ToString());
        Debug.Log("name"+jd["name"]);
        JsonData items = jd["list"];
        for (int i = 0; i < items.Count; i++)
        {
            Debug.Log(items[i]["name"]);
        }
    }

    public void writeJsonToFile(string path, string fileName)
    {
        StringBuilder strB = new StringBuilder();
        JsonWriter jsWrite = new JsonWriter(strB);
        jsWrite.WriteObjectStart();
        jsWrite.WritePropertyName("name");
        jsWrite.Write("caicai");
        jsWrite.WritePropertyName("list");
        jsWrite.WriteArrayStart();
        jsWrite.WriteObjectStart();
        jsWrite.WritePropertyName("name");
        jsWrite.Write("huahua");
        jsWrite.WriteObjectEnd();
        jsWrite.WriteObjectStart();
        jsWrite.WritePropertyName("name");
        jsWrite.Write("huanghuang");
        jsWrite.WriteObjectEnd();
        jsWrite.WriteArrayEnd();
        jsWrite.WriteObjectEnd();

        DirectoryInfo dir = new DirectoryInfo(path);
        if (dir.Exists)
        {
            Debug.Log("dir is exit");
        }
        else
        {
            Directory.CreateDirectory(path);
            Debug.Log("createdir");
        }
        StreamWriter sw;
        if (File.Exists(fileName))
        {
            //sw = File.AppendText(fileName);
            sw = File.CreateText(fileName);
            Debug.Log("appendText");
        }
        else
        {
            sw = File.CreateText(fileName);
            Debug.Log("createText");
        }
         sw.WriteLine(strB);
        sw.Close();
        //AssetDatabase.Refresh();
    }

    public void ReadJsonFromJson()
    {
        json = Resources.Load("TextFile/File") as TextAsset;
        JsonData jd = JsonMapper.ToObject(json.text);
        Debug.Log(jd["name"]);
    }
}


class Person
{
    public string name { get; set; }
    public int age { get; set; }
}

 

### 如何在 Unity 中解析和生成 JSON 数据 #### 使用 `JsonUtility` 进行简单对象的序列化与反序列化 对于简单的 JSON 序列化和反序列化操作,可以使用 Unity 自带的 `JsonUtility` 工具。为了使自定义的数据类能够被正确地转换成 JSON 字符串或从 JSON 字符串中读取,该类需要标记 `[System.Serializable]` 属性[^1]。 ```csharp using UnityEngine; [System.Serializable] public class PlayerData { public int health; public string name; } // 将 C# 对象转为 JSON 字符串 PlayerData player = new PlayerData {health = 100, name = "Hero"}; string jsonString = JsonUtility.ToJson(player); Debug.Log(jsonString); // 由 JSON 字符串恢复为 C# 对象 PlayerData loadedPlayer = JsonUtility.FromJson<PlayerData>(jsonString); Debug.Log(loadedPlayer.name + ": " + loadedPlayer.health); ``` 需要注意的是,`JsonUtility` 不支持复杂的嵌套结构以及某些特定类型的属性,这可能限制其应用场景[^3]。 #### 利用第三方库 LitJson 处理更灵活的情况 当遇到较为复杂的数据模型或是希望拥有更多功能时,则可以选择引入外部库如 LitJson 来完成任务。通过这种方式不仅可以轻松访问 JSON 数组中的元素还可以方便地遍历整个文档树形结构来获取所需的信息[^2]。 下面是一个利用 LitJson 实现异步加载并解析远程 JSON 文件的例子: ```csharp using LitJson; using System.Collections; using UnityEngine; using UnityEngine.Networking; IEnumerator LoadAndParseRemoteJson() { var uri = new System.Uri(Path.Combine(Application.streamingAssetsPath, "data.json")); using (UnityWebRequest request = UnityWebRequest.Get(uri)) { yield return request.SendWebRequest(); if (!request.isNetworkError && !request.isHttpError) { string jsonStr = request.downloadHandler.text; // 假设我们有一个根节点名为 RootObject 的类用于映射返回的结果 RootObject data = JsonMapper.ToObject<RootObject>(jsonStr); foreach(var item in data.items){ Debug.Log(item.ToString()); } } else { Debug.LogError($"Failed to load file: {request.error}"); } } } ``` 此方法允许开发者更加自由地控制如何构建应用程序内部使用的数据表示形式,并且提供了更好的错误处理机制[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值