JSON数据修改的实现
JSON数据的修改
示例代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//C#命名空间(以System开头)
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";
加的字符串为自己想要修改的json文件
读取文件所有内容
//if (!File.Exists(path))
//{
// //写入文件所有内容
// File.WriteAllText(path, "A CodeFarmer");
//}
//else
//{
// Debug.Log(File.ReadAllText(path));
//}
JsonModify();
}
void JsonModify()
{
string path = Application.persistentDataPath + "/data.json";
if (!File.Exists(path))
{
//写入文件所有内容
File.WriteAllText(path, "[1,2,3]");
}
else
{
//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>
<Data>
<ID>123</ID>
<Name>admin</Name>
</Data>
</Root>
XML规则
所有XML元素都须有关闭标签
XML标签对大小写敏感
XML必须正确地嵌套
特殊字符
"<"=>"<"
">"=>">"
"&"=>"&"
"'"=>"'"
"""=>"""
扩展学习
http://www.w3school.com.cn/xml/index.asp
类库
http://www.cnblogs.com/fish-li/archive/2013/05/05/3061816.html
JSON和XML对比
JSON比XML可读性高
同样具有很强的扩展性
XML的解析得考虑子节点父节点,让人头昏眼花,而JSON的解析难度几乎为0
JSON相对于XML来讲,数据的体积小,传递和解析的速度更快。
JSON不使用保留字
XML必须存在一个父节点
该系列专栏为网课课程笔记,仅用于学习参考。