public class Student2
{
public string name;
public int age;
public Student2(int age, string name)
{
this.age = age;
this.name = name;
}
}
public class Robot2
{
public string name = "robot";
public int age = 5;
public bool gender = true;
public int[] ids;
public List<int> ids2;
public Dictionary<int, string> dic;
public Student2 s1;
private float f = 1.4f;
}
public class L2 : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
//使用LitJson进行序列化
//JsonMapper.ToJson(对象)
Robot2 robot = new Robot2();
robot.ids = new int[] { 1, 2, 4 };
robot.ids2 = new List<int>() { 1, 2, 3 };
robot.dic = new Dictionary<int, string>() { { 1, "123" }, { 2, "234" } };
robot.s1 = new Student2(1, "bobo");
string jsonStr = JsonMapper.ToJson(robot);
print(Application.persistentDataPath);
File.WriteAllText(Application.persistentDataPath + "/robot2.json", jsonStr);
//LitJson支持字典,且为null的值在存储时也会存储null
//在自定义类前不需要加特性,但是私有的成员变量不能被序列化
//使用LitJson进行反序列化
//JsonMapper.ToObject(json字符串);
jsonStr = File.ReadAllText(Application.persistentDataPath + "/robot2.json");
//JsonData是LitJson提供的类对象,可以用键值对的形式去访问其中的内容
//JsonData data = JsonMapper.ToObject(jsonStr);
//print(data["name"]);
//print(data["age"]);
Robot2 robot2 = JsonMapper.ToObject<Robot2>(jsonStr);
//虽然支持字典,但如果键是数值在反序列化时会报错
//反序列化自定义类时,自定义类需要有无参无返回值的构造函数,否则会报错
//LitJson可直接读取数据集合
}
}