JSON格式
1、JSON的{}大括号里只有一个对象
{“key”:“value”}大括号里表示这是一个JSON对象,通过键和值来存储对象,key和必须用双引号来包裹,而value键则是看值类型,如果是int类型就不需要双引号
2、JSON文件里可以有多个对象
[{“Account”:“1”,“Password”:“1”},{“Account”:“456”,“Password”:“456”}],文件里可以创建多个对象
JSON格式一个标点符号都不能错,可以去这个网站来校检在线JSON校验格式化工具(Be JSON)
具体代码
创建的json文件里必须要初始化,否则会报空
using LitJson;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
public class Person
{
public string Account { get; set; }
public string password { get; set; }
}
public class Logins : MonoBehaviour
{
public InputField Account;
public InputField Password;
public Button Login;
public Button Enroll;
void Start()
{
string s = Application.dataPath + "/JSON/text.json";
//File.Create(s).Dispose();
Enroll.onClick.AddListener(EnrollButton);
Login.onClick.AddListener(Read);
}
void EnrollButton()
{
if (Account.text.Length != 0)
{
if (Password.text.Length != 0)
{
Write();
print("注册成功");
Account.text = Password.text = null;
}
}
}
void Write()
{
bool b = true;
string s = Application.dataPath + "/JSON/text.json";
string ss = File.ReadAllText(s);
List<Person> list = JsonMapper.ToObject<List<Person>>(ss);
foreach (Person item in list)
{
if (item.Account.Equals(Account.text))
{
if (item.password.Equals(Password.text))
{
b = false;
print("已有该账号");
break;
}
}
}
if (b)
{
Person person = new Person();
person.Account = Account.text;
person.password = Password.text;
list.Add(person);
string sss = JsonMapper.ToJson(list);
File.WriteAllText(s, sss);
}
}
void Read()
{
bool b = false;
string s = Application.dataPath + "/JSON/text.json";
string ss = File.ReadAllText(s);
List<Person> list = JsonMapper.ToObject<List<Person>>(ss);
foreach (Person item in list)
{
if (item.Account.Equals(Account.text))
{
if (item.password.Equals(Password.text))
{
b = true;
break;
}
}
}
if (b)
{
print("登录成功");
Account.text = Password.text = null;
}
else
{
print("账号或密码错误");
Account.text = Password.text = null;
}
}
}