Unity——JSON

Json支持的数据结构

        数字型:short,int,long,float,double

        字符串:“abc”,“你好”,‘abc’        

        布尔类型:true,false

        null:null

        数组(列表):[值1,值2]

        对象(字典):{"键1":"值1","键2":"值2"}

字符含义

        大括号组:对象,字典

        中括号组:数组,列表

        冒号:赋值,左侧是变量或键,右侧为值

        逗号:元素分割符,最后一个元素后,没有逗号

        双引号组:修改变量(可以不加),表示string数据类型

        单引号组:同双引号组

JSON在游戏中的使用

        存储在服务器中的数据

        存储在策划配置的Excel中(Excel -> JSON)

        将Excel中的数据导出为JSON

        填写Excel数据,导出为CSV

在线Excel、CSV转JSON格式-BeJSON.com

C#使用JSON数据

        数据存储(序列化):将C#的数据格式,转化为JSON字符串,存储或传输

        数据使用(反序列化):将JSON字符串中存储的数据,转化为C#可用的数据格式,实现代码逻辑

        序列化(程序数据->JSON字符串)

        反序列化(JSON字符串->程序数据)

Unity的JSON工具

        类名:JsonUtility

        序列化:ToJson()

        反序列化:FromJson()

使用Unity的内置JSON解析工具,将C#数据序列化为JSON字符数据

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class JsonTest : MonoBehaviour
{
    //类产生的对象数据,可以被序列化
    [System.Serializable]
    public class Student { }

    [System.Serializable]
    public class Date 
    {
        public int ID;

        public string Name;

        public bool IsStudent;

        public Student student;

        public List<int> Number;
    }


    void Start()
    {
        Date stu1 = new Date();
        stu1.ID = 1;
        stu1.Name = "Abc";
        stu1.IsStudent = true;
        stu1.student = null;
        stu1.Number = new List<int> { 1, 2, 3 };

        //将C#对象数据,转换为JSON字符串
        string json = JsonUtility.ToJson(stu1);

        Debug.Log(json);
    }

 
}

解析JSON(反序列化) 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class JsonDecode : MonoBehaviour
{
    public class Student { }

    public class Data
    {
        public int ID;

        public string Name;

        public bool IsStudent;

        public Student student;

        public List<int> Number;
    }

    void Start()
    {
        //可以将Unity中以“.json”扩展名结尾的文件,作为Unity的TextAsset数据类型加载
        TextAsset asset = Resources.Load<TextAsset>("Json/test");
        //获取TextAsset内部的文本内容
        string json = asset.text;

        Debug.Log(json);

        //解析JSON(反序列化)
        Data data = JsonUtility.FromJson<Data>(json);

        Debug.Log(data.Name);
    }


}

注意:如果使用Unity的内置解析类,JSON最外层结构必须是对象结构

        当一个类需要存储在另外一个成员变量中时,需要给类声明加特性

解决办法:在json链表的外面再包裹一层对象

        

{
  "Data" : 
  [
    {
      "ID": 1,
      "Name": "羊刀",
      "Description": "加攻速",
      "Level": 3,
      "PriceType": 0
    },
    {
      "ID": 2,
      "Name": "黑皇杖",
      "Description": "用一次短一点",
      "Level": 2,
      "PriceType": 0
    },
    {
      "ID": 3,
      "Name": "龙心",
      "Description": "回血",
      "Level": 3,
      "PriceType": 0
    },
    {
      "ID": 4,
      "Name": "体力丹",
      "Description": "恢复一点hp",
      "Level": 1,
      "PriceType": 1
    }
  ]
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class JsonTable : MonoBehaviour
{
    [System.Serializable]
    public class ItemRow 
    {
        public int ID;
        public string Description;
        public int Level;
        public int PriceType;
    }

    [System.Serializable]
    public class ItemTable 
    {
        public List<ItemRow> Data;
    }

    void Start()
    {
        //加载json道具表的TextAsset
        TextAsset asset = Resources.Load<TextAsset>("Json/item");
        //获取内部文字
        string json = asset.text;
        //解析json
        ItemTable itemRow = JsonUtility.FromJson<ItemTable>(json);

        Debug.Log(itemRow.Data[0].Description);
    }

    
}

LitJson的导入

        1.将LitJson的源代码导入到Unity项目的Assets里

链接:https://pan.baidu.com/s/1CLZKG7NT9wahyJRYireZfg 
提取码:drxe 

使用LitJson可以直接对链表进行操作,不用在外面再包裹一层对象 

[
    {
      "ID": 1,
      "Name": "羊刀",
      "Description": "加攻速",
      "Level": 3,
      "PriceType": 0
    },
    {
      "ID": 2,
      "Name": "黑皇杖",
      "Description": "用一次短一点",
      "Level": 2,
      "PriceType": 0
    },
    {
      "ID": 3,
      "Name": "龙心",
      "Description": "回血",
      "Level": 3,
      "PriceType": 0
    },
    {
      "ID": 4,
      "Name": "体力丹",
      "Description": "恢复一点hp",
      "Level": 1,
      "PriceType": 1
    }
  ]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//引入LitJson命名空间
using LitJson;

public class TestLitJson : MonoBehaviour
{

    [System.Serializable]
    public class ItemRow
    {
        public int ID;
        public string Name;
        public string Description;
        public int Level;
        public int PriceType;
    }


    void Start()
    {
        //加载json道具表的TextAsset
        TextAsset asset = Resources.Load<TextAsset>("Json/item02");
        //获取内部文字
        string json = asset.text;
        //解析json
        List<ItemRow> data = JsonMapper.ToObject<List<ItemRow>>(json);

        Debug.Log(data[0].Name);
    }

   
}

读取字典:

{
  "a" : 1,
  "b" : 2
}
    /// <summary>
    /// 字典
    /// </summary>
    public void TestDictionary()
    {
        TextAsset asset = Resources.Load<TextAsset>("Json/dic");
        string json = asset.text;
        Dictionary<string, int> data = JsonMapper.ToObject<Dictionary<string, int>>(json);
        Debug.Log(data["a"]);
    }

文件的读取与修改

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//输入输出的命名空间
using System.IO;

public class JsonChange : MonoBehaviour
{
  
    void Start()
    {
        //Application应用的相关数据存储在内部
        //unity开发应用必定可写的项目
        string path = Application.persistentDataPath + "/save.json";

        InputText(path);
        OutText(path);
    }

    public void InputText(string path)
    {
        //判断文件石佛营存在,返回的是bool类型
        Debug.Log(File.Exists(path));

        //写入文件所需要的内容
        File.WriteAllText(path, "1234");
    }

    public void OutText(string path)
    {
        //读取文件的所有内容
        Debug.Log(File.ReadAllText(path));
    }
}

Json修改数据

        JsonData是引用类型,所以对象的修改,都会直接影响到原始数据

      public void JsonMdfiy(string path)
    {
        //先判断文件是否存在
        if(!File.Exists(path))
        {
            //如果不存在写入内容
            File.WriteAllText(path, "[1,2,3]");
        }
        else
        {
            //Json文件的内容读取
            string content = File.ReadAllText(path);
            //Json字符串解析为JsonData
            JsonData data = JsonMapper.ToObject(content);
            //修改数据
            data[2] = 2000;

            //将变化的内容写入json
            Debug.Log(data[0]);
            Debug.Log(data[1]);
            Debug.Log(data[2]);
            File.WriteAllText(path,data.ToJson());
        }
    }

 if (!File.Exists(path))
            {
                //外层建一个列表
                JsonData list = new JsonData();              

                //一行的数据
                JsonData row = new JsonData();
                row["Admin"] = Admin.Name;
                row["Pass"] = Admin.passWorld;

                //一行数据加入列表
                list.Add(row);

                //将列表数据写入json文件
                File.WriteAllText(path, list.ToJson());
            }
            else
            {
                //读取原来数据
                string json = File.ReadAllText(path);

                //将新数据加入
                JsonData list = JsonMapper.ToObject(json);

                //一行的数据
                JsonData row = new JsonData();
                row["Admin"] = Admin.Name;
                row["Pass"] = Admin.passWorld;

                //一行数据加入列表
                list.Add(row);

                //写入文件
                File.WriteAllText(path, list.ToJson());
            }

猜你喜欢

转载自blog.csdn.net/m0_51743362/article/details/123806789