Json详解
一.简介
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于阅读和编写,也易于机器解析和生成。以下是JSON存储的主要特点:
1. 易于阅读和编写
简洁性:JSON格式简单,易于理解和编写。
可读性:JSON数据以键值对的形式组织,具有良好的可读性。
2. 轻量级
体积小:JSON文件体积小,适合网络传输。
解析速度快:JSON格式简单,解析速度快。
3. 灵活的数据结构
支持多种数据类型:JSON支持字符串、数字、布尔值、数组和对象等数据类型。
嵌套结构:JSON支持嵌套结构,可以表示复杂的数据关系。
4. 语言无关性
跨平台:JSON可以在不同的编程语言和平台上使用。
广泛支持:几乎所有的编程语言都提供了对JSON的支持。
5. 与JavaScript的紧密集成
JavaScript原生支持:JSON是JavaScript的一个子集,可以在JavaScript中直接使用。
浏览器支持:现代浏览器都提供了对JSON的原生支持。
6. 适合网络传输
轻量级:JSON文件体积小,适合网络传输。
快速解析:JSON格式简单,解析速度快。
7. 数据的兼容性
易于转换:JSON可以轻松转换为其他数据格式,如XML、YAML等。
易于集成:JSON可以与各种系统和应用集成。
8. 缺点
缺乏类型支持:JSON不支持日期类型等复杂数据类型。
安全性问题:JSON数据需要经过验证,以防止恶意数据。
using System.Collections;
using System.Collections.Generic;
using System.IO;
using TMPro;
using UnityEngine;
using UnityEngine.UI;[System.Serializable]//序列化
public class JsonDate
{public string name;public int cont;public bool isWin;
}public class JsonListDate//创建存储列表
{public List<JsonDate> jsonListDate = new List<JsonDate>();
}
public class JsonManager : MonoBehaviour
{JsonDate play1;JsonDate play2;public TextMeshProUGUI play1Text;public TextMeshProUGUI play2Text;public JsonListDate list = new JsonListDate();void Start(){JsonLaod();}void stDate()//初始化信息{play1 = new JsonDate();play1.name = "play1";play1.cont = 0;play1.isWin = false;list.jsonListDate.Add(play1);play2 = new JsonDate();play2.name = "play2";play2.cont = 0;play2.isWin = false;list.jsonListDate.Add(play2);}private void JsonSave()//保存到文件{string path = Application.streamingAssetsPath + "/JsonPath.json";using(StreamWriter sw =new StreamWriter(path)){string json = JsonUtility.ToJson(list,true);sw.WriteLine(json);}}private void JsonLaod()//从文件中加载数据{string path = Application.streamingAssetsPath + "/JsonPath.json";string json;if(File.Exists(path)){using (StreamReader sr = new StreamReader(path)){json = sr.ReadToEnd();//先读}list = JsonUtility.FromJson<JsonListDate>(json);//后转译play1 = list.jsonListDate[0];play2 = list.jsonListDate[1];}else{Debug.Log("列表为空!");stDate();}play1Text.text = play1.cont.ToString();play2Text.text = play2.cont.ToString();}public void OnClickButton(string player){if(player=="play1"){play1.cont += 1;play1Text.text = play1.cont.ToString();}else if(player=="play2"){play2.cont += 1;play2Text.text = play2.cont.ToString();}}public void AllExit(){JsonSave();UnityEditor.EditorApplication.isPlaying = false;//结束运行}
}