【问题标题】:Using JsonUtility.FromJson to deserialize JSON in UnityUnity中使用JsonUtility.FromJson反序列化JSON
【发布时间】:2016-11-11 09:52:19
【问题描述】:

这是我的 JSON 示例:

{"data":[{"id":141,"layoutLabel":"Sameer","hasCustomProb":1},
{"id":214,"layoutLabel":"abc","hasCustomProb":0}],"status":200}

这是我做的课

[System.Serializable]
public class PlayerInfo
{
    public string [] data;
    public int status;
}

这就是我从 JSON 获取“状态”的方式:

PlayerInfo P = JsonUtility.FromJson<PlayerInfo>(json);
Debug.Log(P.status) //returns 200

有人可以帮我获取并保存数据数组还是获取 data.id 和 data.hasCustomProb?我是 C# 和统一的新手。

【问题讨论】:

  • 数据不是字符串[]类型。在您的示例 JSON 中,它是一个对象数组,每个对象都有一个“id”、“layoutLabel”和“hasCustomProb”属性。
  • 这些问题不可以在gamedev.stackexchange.com问吗?

标签: c# json unity3d


【解决方案1】:

你的班级应该是这样的

[System.Serializable]
public class PlayerInfo
{
    public List<ActData> data;
    public int status;
}

[System.Serializable]
public class ActData
{
    public int id;
    public string layoutLabel;
    public int hasCustomProb;
}

【讨论】:

  • 除非您必须从所有变量中删除{ get; set; }。 JsonUtility 无法使用。
  • @Programmer 你是对的。我想确定是否需要 Serializable 属性,因为我刚刚编辑了这个答案?
  • 是的,否则 OP 也会得到空结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 2018-12-18
相关资源
最近更新 更多