1、JSON的{}大括号里只有一个对象
{"key":"value"}大括号里表示这是一个JSON对象,通过键和值来存储对象,key和value键必须用双引号来包裹
2、JSON文件里可以有多个对象
[{"Account":"1","Password":"1"},{"Account":"456","Password":"456"}],文件里可以创建多个对象
JSON格式一个标点符号都不能错,可以去这个网站来校检在线JSON校验格式化工具(Be JSON)
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using LitJson;//注意,必须引入LitJson插件,否则引入不了这个命名空间
public class UI : MonoBehaviour
{
public InputField D_Account, D_Password;
public InputField Z_Account, Z_Password, Z_Password1;
public Button D_Regiester, Lon;
public Button Z_Register, Return;
public RectTransform Pan1, Pan2;
void Start()
{
string path = Application.dataPath + "/JSON/Person.json";//JSON文件资源路径;
//File.Create(path).Dispose();//创建完JSON文件自动释放文件流所占用的资源;
//注意:创建完JSON文件里必须初始化数据,否则运行会报空
[{"Account":"1","Password":"1"},{"Account":"456","Password":"456"}]
D_Regiester.onClick.AddListener(D_Regiesters);
Return.onClick.AddListener(Returns);
Z_Register.onClick.AddListener(Z_Registers);
Lon.onClick.AddListener(Lons);
}
private void Lons()
{
Read();
}
private void Z_Registers()
{
Write();
}
private void Returns()
{
Pan1.gameObject.SetActive(true);
Pan2.gameObject.SetActive(false);
Z_Account.text = null;
Z_Password.text = null;
Z_Password1.text = null;
}
private void D_Regiesters()
{
Pan1.gameObject.SetActive(false);
Pan2.gameObject.SetActive(true);
D_Account.text = null;
D_Password.text = null;
}
void Write()
{
if (Z_Password.text == Z_Password1.text)
{
bool f = true;
string path = Application.dataPath + "/JSON/Person.json";
string str = File.ReadAllText(path);//读出序列化后的文件
List<JSON> jsons = JsonMapper.ToObject<List<JSON>>(str);//反序列化
foreach (JSON js in jsons)
{
if (js.Account.Equals(Z_Account.text))
{
f = false;
print("账号重复");
break;
}
}
if (f)
{
print("注册成功");
JSON jSON = new JSON();//创建新用户
jSON.Account = Z_Account.text;
jSON.Password = Z_Password.text;
jsons.Add(jSON);//将新创建的用户添加至上面反序列化后的用户集合中
string s = JsonMapper.ToJson(jsons);//将添加后的用户集合序列化并写入
File.WriteAllText(path, s);
}
}
else
{
print("密码不一致");
}
}
void Read()
{
string path = Application.dataPath + "/JSON/Person.json";
string str = File.ReadAllText(path);
List<JSON> jsons = JsonMapper.ToObject<List<JSON>>(str);
for (int i = 0; i < jsons.Count; i++)//如果用foreach遍历的话会遍历JSON里面所有的数据,会把所有的结果输出出来
{
if (jsons[i].Account.Equals(D_Account.text) && jsons[i].Password.Equals(D_Password.text))
{
print("登录成功");
break;
}
else if (jsons.Count == i + 1)
{
print("登录失败");
}
}
}
public class JSON//封装类
{
public string Account { get; set; }
public string Password { get; set; }
}
}