【发布时间】:2020-10-13 15:09:43
【问题描述】:
我正在尝试读取在 Unity 脚本中读取的 json 数组的变量。 这就是我所拥有的:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
public class json_example02 : MonoBehaviour
{
public string[] newObject;
void Start()
{
Debug.Log("jsonScript start");
// create object
jasonClass newObject = new jasonClass();
// read from json file: succesful
string jsonread = File.ReadAllText(Application.dataPath + "/valuesexample.json");
newObject = JsonUtility.FromJson<jasonClass>(jsonread);
Debug.Log(newObject.Values.Length);// reads correctly
// trying to acces variables here, but it returns empty
Debug.Log("Values: " + newObject.Values[0]);
Debug.Log("Values: " + newObject.Values[1]);
Debug.Log("Values: " + newObject.Values[2]);
// write to file: succesful
string jsonwrite = JsonUtility.ToJson(newObject);
File.WriteAllText(Application.dataPath + "/saveFileReturn.json", jsonwrite);
}
[Serializable]
public class jasonClass
{
public Valuesarray[] Values;
}
[Serializable]
public class Valuesarray
{
public string Text;
//public string Text2;
}
}
这是json读取文件的格式:
{"Values":[{
"Text":"A"
},
{
"Text":"B"
},
{
"Text":"C"
},
{
"Text":"D"
},
{
"Text":"E"
}]
}
检查读取和写入另一个文件。输出:
{"Values":[{"Text":"A"},{"Text":"B"},{"Text":"C"},{"Text":"D"},{"Text":"E"}]}
到目前为止一切都很好,但我不明白如何通过索引号读取各个变量,如下所示:
Debug.Log("Values: " + newObject.Values[0]);
返回空。 如何通过索引号访问这些变量?
提前致谢。
【问题讨论】: