Unity—JSON

每日一句:手简素中,感生活恬淡,心有所期,忙而不茫

目录

服务器

常见的服务器语言

Unity的开发语言

JSON

功能:

JSON最简单的格式

JSON工具

支持的数据结构(C#对于JSON)

字符含义

JSON的游戏中使用

Unity的JSON工具

类名:JsonUtility

序列化:ToJson()

反序列化:FromJson()

LitJson

列表

   字典

  列表嵌套类

数据表

修改JSON数据

XML

支持数据类型

XML规则

JSON和XML对比

作业:

请使用JSON完成注册和登录功能(JsonUtility实现,LitJson的JsonData实现,LitJson的List实现)

*JsonData

*JsonUtility


服务器

用来存储和处理数据的一台或一组电脑

常见的服务器语言

C++、Java、Nodejs(JavaScript)、PHP、Python、Go

Unity的开发语言

C#、Lua

JSON

全名:JavaScript Object Notation

功能:

JavaScript对象标记语言,是一种跨平台,跨语言,轻量级的数据交换和存储格式

JSON最简单的格式

JSON写法

{“Username”:”admin”,”Passward”:”123”}

C#

class OneRow

{

    public string Username;

    public string Password;

}

var obj = new OneRow();

obj.Username = "admin";

obj.Password = "123";

JSON工具

在线JSON校验格式化工具(Be JSON)

支持的数据结构(C#对于JSON)

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

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

布尔:true,false

null:null

数组(列表):【值1,值2】

[1, 2, 3]

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

{

    "a": 1,

    "b": true,

    "c": "abc",

    "d": null,

    "e": [1, 2, 3]

}

Bit    0001

Byte      00000001    00000000~11111111

Ushort   0~65535

new List<int>() { 1, 2, 3 };  C#

new Dictionary<string, int> { { "a", 1 }, { "ab", 2 } }; C#

数组里套对象

字符含义

大括号组:对象,字典

中括号组:数组,列表

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

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

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

单引号组:同双引号组

JSON的游戏中使用

存储在服务器中的数据

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

将Excel中的数据导出为JSON

填写Excel数据

将Excel数据,导出为csv

通过文本编辑器,打开CSV内部内容,复制

将数据贴到转换工具上

分隔符表示,列间的分隔符,CSV列通过逗号分割,所以填写逗号

值全部使用字符串,不选,否则会影响C#数据类型,转换方式,按行转换对象(单元格数据和表头的列名产生赋值)

Unity的JSON工具

类名:JsonUtility

序列化:ToJson()

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

//测试序列化(C#数据——>JSON数据)

[System.Serializable]

public class SubData

{ }

[System.Serializable]//类产生的对象数据,可以被序列化后存储

public class Data

{

    //数字型

    public int ID;

    //字符串型

    public string Name;

    //布尔型

    public bool IsStudent;

    //对象型

    public SubData Sub;

    //数组或列表

    public List<int> Numbers;

}

public class JsonEncode : MonoBehaviour

{

    // Start is called before the first frame update

    void Start()

    {

        var obj = new Data();

        obj.ID = 1;

        obj.Name = "abc";

        obj.IsStudent = true;

        obj.Sub = null;

        obj.Numbers = new List<int> { 1, 2, 3 };

        //将C#对象数据,转换为JSON字符串

        string json = JsonUtility.ToJson(obj);

        Debug.Log(json);

    }

}

注意:JSON最外层结构必须是对象结构

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

[System.Serializable]

存储游戏对象GameObject方法—存它的预制体,在JSON里存它的路径

————————————————————————————————————————

反序列化:FromJson()

//JSON格式存储的数据

Unity的JSON工具,解析JSON后,将数据存储在这个类型的对象中,因为JsonUtility.FromJson<T>()需要提供C#数据类型与JSON对应,所以需要在C#中定义数据类型

将j变量中存储的JSON结构,转化为C#的类型数据

//T:C#接收类型   参数:JSON字符串

public class ItemRow
{
    public int ID;
    public string Name;
    public string Description;
    public int Level;
    public int PriceType;
}
[System.Serializable]
public class ItemTable
{
    public List<ItemRow> Data;
}
public class JsonTable : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        //加载JSON道具表的TextAsset
        TextAsset asset = Resources.Load<TextAsset>("Json/item");
        //获取内部文字
        string json = asset.text;
        Debug.Log(json);
        //解析JSON
        ItemTable d = JsonUtility.FromJson<ItemTable>(json);
        //Item表对象下Data成员变量下的第一条数据下的Name成员变量(羊刀)
        Debug.Log(d.Data[0].Name);
    }
}

LitJson

序列化

JsonMapper.ToJson()

反序列化

获得JsonData: JsonMapper.ToObject()

获得指定类型:JsonMapper.ToObject<T>()

注意:

反序列化不要求最外层是对象

对象内部存储对象不需要[System.Serializable]修饰Class

//引入LitJson命名空间

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using LitJson;

public class LitItemRow

{

    public int ID;

    public string Name;

    public string Description;

    public int Level;

    public int PriceType;

}

public class TestLitJson : MonoBehaviour

{

    // Start is called before the first frame update

    void Start()

    {

        //TestList();

        //TestDictionary();

        //TestListItemRow();

        //TestJsonData();

        TestToJson();

    }

列表

    public void TestList()

    {

        //加载JSON道具表的TextAsset

        TextAsset asset = Resources.Load<TextAsset>("Json/Lit_item");

        //获取内部文字

        string json = asset.text;

        Debug.Log(json);

        List<int> data = JsonMapper.ToObject<List<int>>(json);

        Debug.Log(data[0]);

}

   字典

public void TestDictionary()

    {

        //加载JSON道具表的TextAsset

        TextAsset asset = Resources.Load<TextAsset>("Json/dic");

        string json = asset.text;

        Dictionary<string, int> d = JsonMapper.ToObject<Dictionary<string, int>>(json);

        Debug.Log(d["a"]);

}

  列表嵌套类

  public void TestListItemRow()

    {

        TextAsset asset = Resources.Load<TextAsset>("Json/item");

        string json = asset.text;

        List<LitItemRow> d = JsonMapper.ToObject<List<LitItemRow>>(json);

        //也可以列表套字典,需要保证所有行中,键的类型一致,值的类型一致

        //List<Dictionary<string, string>> d1 = JsonMapper.ToObject<List<Dictionary<string, string>>>(json);

    }

数据表

    public void TestJsonData()

    {

        TextAsset asset = Resources.Load<TextAsset>("Json/item");

        string json = asset.text;

        JsonData d = JsonMapper.ToObject(json);

        //总的数据

        //一行数据

        JsonData row = d[2];

        Debug.Log(row["Description"]);

        //循环获取JsonData中的值

        for(int i=0;i<d.Count;i++)

        {

            Debug.Log((int)d[i]["ID"]);

            Debug.Log(d[i]["Name"].ToString());

        }

}

    public void TestToJson()

    {

        Debug.Log(JsonMapper.ToJson(new List<int>() { 111, 222, 333 }));

        Debug.Log(JsonMapper.ToJson(new Dictionary<string,int>() { {"aa",11 }, { "bb", 22 } }));

        JsonData data = new JsonData();

        data["user"] = "admin";

        data["id"] = 123;

        data["is_student"] = true;

        Debug.Log(data.ToJson());

    }

}

修改JSON数据

using System.IO;

using LitJson;

public class JsonChange : MonoBehaviour

{

    // Start is called before the first frame update

    void Start()

    {

        //Application应用的相关数据存储在内部

        //Unity开发的应用必定可写目录

        Debug.Log(Application.persistentDataPath);

        string path = Application.persistentDataPath + "/save.json";

        //C:/Users/lenovo1/AppData/LocalLow/DefaultCompany/JsonCode/save.json

        //检查文件是否存在

        if (!File.Exists(path))

        {

            //写入文件所有内容

            File.WriteAllText(path, "[1,2,3]");

        }

        else

        {

            //读取文件所有内容

            Debug.Log(File.ReadAllText(path));

            //JSON文件内容读取(JSON字符串)

            string content = File.ReadAllText(path);

            //JSON字符串解析为JsonData

            JsonData data = JsonMapper.ToObject(content);

            //修改第二条数据

            data[2] = 300;

            //最后将修改后的数据,再转换为JSON字符串,写入文件中

            File.WriteAllText(path, data.ToJson());

        }

    }

}

XML

全名:Extensible Markup Language

可扩展标记语言,标准通用标记语言的子集,是一种用于标记电子文件使其具有结构体的标记语言

支持数据类型

数字,字符串,布尔,数组(链表),对象,null

示例

{

     "Username": "root",

     "Password": "123"

}

<?xml version=”1.0” encoding=”UTF-8”?>

<Root>

          <Username v=”123”>root</Username>

          <Password> 123</Password>

</Root>

友情提示:如果使用代码进行CSV文件转JSON文件,记得Excel导出的csv文件是GB2312的字符编码,转换前,需要将文件内容字符集转换为UTF-8

XML规则

所有XML元素都须有关闭标签

XML标签对大小写敏感

XML必须正确地嵌套

特殊字符

“<” =>“&It”         “>” => “&gt”

“&” => “&amp”       “’” => “&apos”

“”” => “&quot”

JSON和XML对比

JSON和XML可读性高

同样具有很强的扩展性

XML的解析得考虑子节点父节点,让人头昏眼花,而JSON的解析难度几乎为0

JSON相对于XML来讲,数据的体积小,传输和解析的速度更快

JSON不使用保留字

XML必须存在一个父节点

作业:

请使用JSON完成注册和登录功能(JsonUtility实现,LitJson的JsonData实现,LitJson的List实现)

*JsonData

//注册

publlic void RegisterClick()

{

        if(!File.Exists(Config._UserNumer))

        {

            //外层创建一个列表

            JsonData list = new JsonData();

            //一行数据

            JsonData row = new JsonData();

            row["Username"] = username;

            row["Password"] = password;

            //一行数列加入列表

            list.Add(row);

            //将列表写入JSON文件

            File.WriteAllText(Config._UserNumer, list.ToJson());

        }

        else

        {

            //读取原来数据

            string json = File.ReadAllText(Config._UserNumer);

            //解析JSON

            JsonData list = JsonMapper.ToObject(json);

            //去重复(遍历所有老数据的用户名,和新用户名进行对比,

            //如果发现用户名已经存在,应该给用户提示,并让用户修改)

            for (int i = 0; i < list.Count; i++)

            {

                if(username==list[i]["UserName"].ToString())

                {

                    Debug.Log("用户名已经存在");

                    return;

                }

            }

            //一行数据

            JsonData row = new JsonData();

            row["UserName"] = username;

            row["Password"] = password;

            //将新数据加入

            list.Add(row);

            //写入文件

            File.WriteAllText(Config._UserNumer, list.ToJson());

        }

}

//登录

public void LoginClick()
    {
        if(!File.Exists(Config._UserNumer))
        {
            Debug.Log("登录失败");
        }
        else
        {
            //读取文件内容
            string json = File.ReadAllText(Config._UserNumer);
            //解析为JsonData
            JsonData list = JsonMapper.ToObject(json);
            bool success = false;
            //遍历JsonData,检查是否存在用户名,且密码是否一致
            for (int i = 0; i < list.Count; i++)
            {
                if (username == list[i]["UserName"].ToString()&&password==list[i]["Password"].ToString())
                {
                    success = true;
                    break;
                }
            }
            if (success)
            {
                Debug.Log("登陆成功");
            }

            else
            {
                Debug.Log("登录失败");
            }
        }

*JsonUtility


[Serializable]
public class UserData
{
    [Serializable]
    public class Row
    {
        public string UserName;
        public string Password;       
    }
    public List<Row> Data;
}    

public void Register_JsonUtility()
    {
        if(!File.Exists(Config._UserNumer))
        {
            //创建对象
            UserData d = new UserData();
            //创建类的子类对象
            UserData.Row row = new UserData.Row();
            row.UserName = username;
            row.Password = password;
            d.Data = new List<UserData.Row>();
            d.Data.Add(row);
            //序列化
            string json = JsonUtility.ToJson(d);
            File.WriteAllText(Config._UserNumer, json);
        }
        else
        {
            //读取原来数据
            string json = File.ReadAllText(Config._UserNumer);
            //解析JSON
            UserData d = JsonUtility.FromJson<UserData>(json);
            for(int i=0;i<d.Data.Count;i++)
            {
                if (username == d.Data[i].UserName)
                {
                    Debug.Log("用户名存在");
                }
            }
            UserData.Row row = new UserData.Row();
            row.UserName = username;
            row.Password = password;
            //添加用户
            d.Data.Add(row);
            File.WriteAllText(Config._UserNumer, JsonUtility.ToJson(d));
        }
    }

  • 19
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值