Unity之JSON(数据存储)

JSON(JavaScript Object Notation, JS对象简谱)是一种轻量级的数据交换格式

JSON格式:以,"[",开始,"]",结束,值之间使用","英文逗号分隔

[{
    "Id": 101,
    "Name": "无影脚"
}]

JSON格式验证网站:https://www.bejson.com/

一、以JSON格式存储数据

  1. 创建技能类 Skill

  1. 封装Id和Name字段,创建构造方法

public class Skill
{
    public string Id { get; set; }
    public string Name { get; set; }
    public Skill()
    {
    }
    public Skill(string id, string name)
    {
        Id = id;
        Name = name;
    }
}
  1. 创建Skill类型的List集合

  1. 创建三个Skill对象,传参调用有参的构造方法(可以直接插入数据,看个人选择)

  1. Write方法:写入数据,path:文件路径(文件后缀可以为.json格式,这里是.txt)

  1. lit.Add():添加对象

  1. jsonDate:JSON格式字符串;for循环为读取list集合的字段,通过JsonMapper.ToJson()方法转换为JSON格式

  1. 转码:为了防止中文乱码,转换为UTF-8

  1. 通过File.WriteAllText()写入文件

 Regex reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})");
        jsonDate = reg.Replace(jsonDate, delegate (Match m) { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); });

温馨提示:

using UnityEngine;

using LitJson;

using System.IO;

using System;

using System.Text.RegularExpressions;

猜你喜欢

转载自blog.csdn.net/m0_74427422/article/details/129540637