Unity 读取Json常用的两种方式

使用的是Litjson

1、读取本地Json

    public void ReadJson()
    {
        StreamReader streamReader = new StreamReader(Application.dataPath + "/XXX.json");
        string str = streamReader.ReadToEnd();
        json = JsonMapper.ToObject(str);
    }

2、请求http(强烈建议先下载到本地再读取

    private IEnumerator GetInterface(string uri)
    {
        using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
        {
            yield return webRequest.SendWebRequest();
            if (webRequest.isNetworkError)
            {
                Debug.LogError(uri + "请求错误:" + webRequest.error);
            }
            else
            {
                Debug.Log(webRequest.downloadHandler.text);
                //保存本地
                string savePath = Application.streamingAssetsPath + "XXX.json";
                File.WriteAllText(savePath, Regex.Unescape(webRequest.downloadHandler.text));
                //读取
                StreamReader streamReader = new StreamReader(savePath);
                string str = streamReader.ReadToEnd();
                JsonData json = JsonMapper.ToObject(str);
                streamReader.Close();

            }
        }
    }

 

你可能感兴趣的:(Unity 读取Json常用的两种方式)