【发布时间】:2018-01-26 20:55:11
【问题描述】:
这是我用于测试目的的 JSON 文件:
{"timestamp":4455518515,"profileId":"5asd15qwe11as2d12q1sd","profileName":"player01",
"textures":{"material":{"url":"http://materialurl.com/aksjd54854we5a4sd.png"}}}
我想访问纹理 -> 材料 -> url,但我做不到。这是我的代码:
public class JsonTest : MonoBehaviour {
string json;
string path;
// Use this for initialization
void Start () {
path = Application.streamingAssetsPath + "/json.txt";
json = File.ReadAllText(path);
MaterialJson test = JsonUtility.FromJson<MaterialJson>(json);
Debug.Log(test.timestamp);
Debug.Log(test.profileId);
Debug.Log(test.profileName);
Debug.Log(test.textures);
}
}
[Serializable]
public class MaterialJson
{
public double timestamp;
public string profileId;
public string profileName;
public string textures;
}
前三个变量没有问题。但是textures 在调试日志中返回 null。我不知道如何在textures 中获取嵌套变量。 unity的JsonUtility 有能力吗?我找不到关于统一文档的任何信息。
它与下面的代码完美配合:(感谢@mrfreester)
[Serializable]
public class MaterialJson
{
public double timestamp;
public string profileId;
public string profileName;
public Textures textures;
}
[Serializable]
public class Textures
{
public Material material;
}
[Serializable]
public class Material
{
public string url;
}
Debug.Log(test.textures.material.url);
【问题讨论】:
-
纹理不是字符串而是 JSON 对象
-
Debug.Log(test.textures.material);是什么意思? -
这不是我有大量经验的领域......但看起来你期待
textures成为string这里......public string textures.. .但是它是你的json中的一个对象。您可能需要创建一个 Serializable 类textures,其中包含一个material类,如果您希望它与您的 json 一起使用,它包含一个public string url。 -
@Quintium 是的,但我也不知道如何解析该对象。
-
@mrfreester 哦,它已使用此代码 Debug.Log(test.texture.material.url);十分感谢你的帮助。你可以把它写成一个解决方案
标签: c# json unity3d deserialization