Menu
CoddyTech

JsonUtility

本课属于 Coddy Unity 学习旅程的“Unity 游戏架构”单元。第 30 课,共 64 课。

JSON 是用于存储对象值的文本,因此可以记录、发送或写入文件。JsonUtility.ToJson(obj) 会将对象转换为 JSON,JsonUtility.FromJson<T>(json) 会据此创建一个新的 T。JsonUtility 遵循 Inspector 使用的规则,因此适用于带有 [System.Serializable] 的类:

[System.Serializable]
public class PlayerProfile
{
    public string playerName = "Ana";
    public int level = 7;
    public List<string> badges = new List<string> { "Explorer", "Sharpshooter" };
    [SerializeField] private float hoursPlayed = 12.5f;
    private int secretCode = 1234;
    public int Rank { get; set; } = 3;
}
string json = JsonUtility.ToJson(new PlayerProfile());
// {"playerName":"Ana","level":7,"badges":["Explorer","Sharpshooter"],"hoursPlayed":12.5}
PlayerProfile copy = JsonUtility.FromJson<PlayerProfile>(json);

secretCode 和 Rank 不会出现在结果中。JsonUtility 会写入公共字段和标记了 [SerializeField] 的私有字段,除此之外不会写入其他内容:不包括属性、静态字段和未标记的私有字段。Dictionary 字段也会被跳过,类没有标记 [System.Serializable] 的字段也一样。这些字段同样不会显示在 Inspector 中。JsonUtility.ToJson(obj, true) 会将相同的 JSON 分散到多行中,更容易阅读。

类中的列表会被写入,就像 badges 一样。单独的列表则不会:JsonUtility 要求顶层是一个对象,因此,对于包含 10、20 和 30 的 List<int>,调用 JsonUtility.ToJson(scores) 会返回 {}。把列表放进一个类中再进行转换;包含同一个列表的 ScoreBoard 会被写成 {"scores":[10,20,30]}:

[System.Serializable]
public class ScoreBoard
{
    public List<int> scores;
}
challenge icon

挑战

中等

将团队分享为 JSON 代码。

  1. 在 CharacterBuild 中,将 Strength 设为字段:public int strength;,并将 agility 标记为 [SerializeField]。
  2. 在它下方,编写一个带有 [System.Serializable] 的 Team 类,其中包含 public List<CharacterBuild> heroes;。在 TeamCode 中,将列表设为 public Team team;,并记录它的 JSON。
  3. LoadCode 将 code 读入 team,并记录 Loaded 3 heroes。

按“开始”,然后按 Space:团队会显示为 JSON。接着点击“检查”。

亲手试试

using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class CharacterBuild
{
    public string hero;
    public int Strength { get; set; }
    private int agility;
}

Unity 游戏架构中的所有课

自己练习: Unity 在线编辑器