JSON相關(guān)
json是國際通用語言,可以跨平臺(tái)(游戲,軟件,網(wǎng)頁,不同OS)使用,
json語法較為簡單,使用更廣泛。json使用鍵值對(duì)來存儲(chǔ)。
認(rèn)識(shí)json文件
//注意字典類型存儲(chǔ)時(shí),鍵是以string類型存儲(chǔ)的 需要添加“”
{
"name": "TonyChang",
"age":21,
"sex":true,
"Float": 2.5,
"arrarys":[1,5,9],
"friends": [{"name": "Tom","age":21, "sex":true,"Float": 2.8},
{"name": "Peter","age":17, "sex":true,"Float": 3.5},
{"name": "Jack","age":25, "sex":true,"Float": 5.0}
],
"university": {"address": "唐山","province":"河北"},
"dic": {"1":"125","2": 911},
"son": null
}
Excel轉(zhuǎn)換為JSON文件:
使用網(wǎng)站來轉(zhuǎn)換:bejson
挖坑-----》開發(fā)一個(gè)工具,使各種類型存儲(chǔ)文件進(jìn)行轉(zhuǎn)換。
Json的讀寫:
-
jsonUtlity中的使用:
string jisonStr = JsonUtility.ToJson(_writer); File.WriteAllText(Application.persistentDataPath+"/DemoJson1.json",jisonStr);
轉(zhuǎn)儲(chǔ)為JSON時(shí)要點(diǎn):
- float存儲(chǔ)時(shí)看起來會(huì)有一些誤差
- 自定義類序列化要添加序列化特性[System.Serializable]
- 想要序列化私有變量,需要添加序列化特性[SerializeField]
- JsonUtility不支持字典
- JsonUtility存儲(chǔ)對(duì)象時(shí)候不會(huì)為null是默認(rèn)值的數(shù)值
完整的類
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
namespace Building.JSON
{
public class Writer
{
public string name;
public int age;
public bool sex;
[SerializeField]
protected float numberF = 3.15f;
[SerializeField]
private double numberD = 6.15;
public List<int> Array;
public IDCard idcard;
}
[Serializable]
public class IDCard
{
public int stu_id;
public int cl_id;
}
public class JsonPractice:MonoBehaviour
{
private Writer _writer;
private void Awake()
{
_writer = new Writer();
_writer.name = "TonyCode";
_writer.sex = true;
_writer.age = 21;
_writer.Array = new List<int>() {1, 2, 3, 4, 5};
_writer.idcard = new IDCard();
_writer.idcard.cl_id = 256;
_writer.idcard.cl_id = 206;
string jisonStr = JsonUtility.ToJson(_writer);
File.WriteAllText(Application.persistentDataPath+"/DemoJson1.json",jisonStr);
print(Application.persistentDataPath);
}
}
}
存儲(chǔ)生成的json文件內(nèi)容。
反序列化:
string jsonStrRead = File.ReadAllText(Application.persistentDataPath + "/DemoJson1.json");
//反序列化
Writer writer01 = JsonUtility.FromJson<Writer>(jsonStrRead);
Writer writer02=JsonUtility.FromJson(jsonStrRead,typeof(Writer)) as Writer;
注意:使用JsonUtility.FromJson進(jìn)行反序列化時(shí)候接受對(duì)象是一個(gè)對(duì)象,不能是一個(gè)數(shù)據(jù)集合來接受Json中存儲(chǔ)的數(shù)據(jù)內(nèi)容。并且json的編碼格式必須為UTF-8。
JSON文件的寫入與讀取,本質(zhì)是對(duì)text文本的讀寫,所以會(huì)調(diào)用File類中對(duì)text文本相關(guān)的方法。
先將類轉(zhuǎn)換為string字符串(Json文件格式的字符串),然后調(diào)用文件方法進(jìn)行讀寫。
2.LitJson(第三方開發(fā)的工具包)
//使用LitJson存儲(chǔ)
string jsonStr2=JsonMapper.ToJson(_writer);
File.WriteAllText(Application.persistentDataPath+"/DemoJson2.json",jsonStr);
注意:(區(qū)別JsonUtility)
- 不能序列化private變量;
- 對(duì)于自定義類不需要添加序列化特性就可以進(jìn)行序列化;
- 支持字典類型,建議字典類型的鍵的類型為“string”;
- 可以準(zhǔn)確保存null類型;
//使用LitJson讀(反序列化)
string jsonStrRead3 = File.ReadAllText(Application.persistentDataPath + "/DemoJson2.json");
//方法一
JsonData data = JsonMapper.ToObject(jsonStrRead3);
print(data["name"]);
//方法二 (使用較多)
Writer writer03= JsonMapper.ToObject<Writer>(jsonStrRead3);
讀取數(shù)據(jù)集合:
//數(shù)據(jù)集合中元素類型
public class RoleInfo
{
public int hp;
public int speed;
public int volume;
public string resName;
public int scale;
}
//讀取數(shù)據(jù)集合
string jsonStrRoleList = File.ReadAllText(Application.persistentDataPath + "/RoleInfo.json");
List<RoleInfo> roleInfos = JsonMapper.ToObject<List<RoleInfo>>(jsonStrRoleList);
foreach (var roleInfo in roleInfos )
{
print(roleInfo.hp+" "+roleInfo.speed+" "+roleInfo.resName);
}
RoleInfo.json內(nèi)容
[
{"hp":4,"speed":6,"volume":5,"resName":"Airplane/Airplane1","scale":15},
{"hp":3,"speed":7,"volume":4,"resName":"Airplane/Airplane2","scale":15},
{"hp":2,"speed":8,"volume":3,"resName":"Airplane/Airplane3","scale":15},
{"hp":10,"speed":3,"volume":10,"resName":"Airplane/Airplane4","scale":6},
{"hp":6,"speed":5,"volume":7,"resName":"Airplane/Airplane5","scale":10}
]
讀取字典:
//讀取字典
//注意字典元素內(nèi)容最后一個(gè)不應(yīng)當(dāng)添加逗號(hào)
string jsonStrDic = File.ReadAllText(Application.persistentDataPath + "/JsonDic.json");
Dictionary<string, int> games = JsonMapper.ToObject<Dictionary<string, int>>(jsonStrDic);
foreach (KeyValuePair<string,int> kv in games)
{
print(kv.Key+" "+kv.Value);
}
JsonDic.json中內(nèi)容:
{
"Tony": 100,
"Jack": 125,
"Pony": 156,
"Tom": 126
}
注意:
- litJson支持字典存儲(chǔ),字典鍵的類型為string
- 自定義類結(jié)構(gòu)一定要有無參構(gòu)造函數(shù)
- LitJson可以直接讀取數(shù)據(jù)集合
- LitJson讀取字典元素時(shí)候 字典內(nèi)容最后一個(gè)不可以加逗號(hào)(可能反序列化失?。?/strong>
對(duì)比JsonUtility和JsonLit二者使用:
相同:文章來源:http://www.zghlxwxcb.cn/news/detail-747820.html
- 二者都是對(duì)json文件進(jìn)行序列化與反序列化的工具類
- 二者都是靜態(tài)調(diào)用,使用其中的方法
- json的格式必須為UTF-8格式
區(qū)別:LitJson對(duì)比JsonUtility文章來源地址http://www.zghlxwxcb.cn/news/detail-747820.html
- 對(duì)于空對(duì)象,LitJson對(duì)可以存儲(chǔ)null類型,而后者只存儲(chǔ)對(duì)應(yīng)的默認(rèn)數(shù)據(jù)數(shù)據(jù)值
- LItJson支持?jǐn)?shù)據(jù)集合的讀取,而后者需要將其轉(zhuǎn)換為對(duì)象內(nèi)部的數(shù)組才可以讀取,讀取存儲(chǔ)結(jié)果為對(duì)象類型,而非數(shù)據(jù)集類型。
- LitJson支持對(duì)字典的存取,字典的鍵的類型為string
- LitJson存儲(chǔ)茲定于數(shù)據(jù)類型時(shí)候無需添加序列化特性,而后者需要
- LitJson不支持對(duì)priivate數(shù)據(jù)內(nèi)容的序列化,后者使用時(shí)候添加序列化特性則可以完成存儲(chǔ)
- LitJson要求自定義數(shù)據(jù)類型必須有無參構(gòu)造,而JsonUtility則不需要
Json讀存的工具類:
using System.IO;
using LitJson;
using UnityEngine;
namespace Building.JSON
{
public enum SaveJsonType
{
JsonUtility,
LitJson
}
public class JsonManager
{
private static JsonManager instance=new JsonManager();
public static JsonManager Instance => instance;
private JsonManager()
{
}
/// <summary>
/// 存儲(chǔ)Json方法
/// </summary>
/// <param name="data">要存儲(chǔ)的數(shù)據(jù)類</param>
/// <param name="FileName">存儲(chǔ)文件名稱</param>
/// <param name="type">存儲(chǔ)方法</param>
public void SaveJson(object data, string FileName,SaveJsonType type=SaveJsonType.LitJson)
{
//確定路徑
string path = Application.persistentDataPath + "/"+FileName+ ".json";
string jsonStr="";
switch (type)
{
case SaveJsonType.LitJson:
jsonStr = JsonMapper.ToJson(data);
break;
case SaveJsonType.JsonUtility:
jsonStr = JsonUtility.ToJson(data);
break;
}
//寫入文件
File.WriteAllText(path,jsonStr);
}
/// <summary>
/// 讀取json方法
/// </summary>
/// <param name="FileName">讀取json的名稱</param>
/// <param name="type">讀取方式</param>
/// <typeparam name="T">讀取json文件中數(shù)據(jù)類型</typeparam>
/// <returns></returns>
public T LoadJson<T>(string FileName, SaveJsonType type = SaveJsonType.LitJson) where T : new()
{
//確定路徑
string path = Application.persistentDataPath + "/"+FileName+ ".json";
if (!File.Exists(path))
{
path=Application.streamingAssetsPath+"/"+FileName+".json";
if (!File.Exists(path))
{
return new T();
}
}
string jsonStrRead=File.ReadAllText(path);
T data = default(T);
switch (type)
{
case SaveJsonType.LitJson:
data=JsonMapper.ToObject<T>(jsonStrRead);
break;
case SaveJsonType.JsonUtility:
data= JsonUtility.FromJson<T>(jsonStrRead);
break;
}
return data;
}
}
}
到了這里,關(guān)于Unity學(xué)習(xí)筆記--數(shù)據(jù)持久化Json的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!