using UnityEngine;
using System.Collections;
using System;
using System.IO;
using System.Collections.Generic;
using LitJson;
/// <summary>
/// 读取Json
/// </summary>
public class ReadWriteJson
{
private static ReadWriteJson instances;
public static ReadWriteJson Instances
{
get
{
if (instances == null)
{
return instances = new ReadWriteJson();
}
return instances;
}
}
private ReadWriteJson()
{
root = new Root();
path = Application.persistentDataPath + "/Json.json";
}
public Root root;
public string path;
/// <summary>
/// 读Json,并且保存数据
/// </summary>
public void ReadJson()
{
if (File.Exists(path))
{
StreamReader streamreader = new StreamReader(path);//读取数据,转换成数据流
JsonReader js = new JsonReader(streamreader);//再转换成json数据
root = JsonMapper.ToObject<Root>(js);//读取
streamreader.Close();
}
}
/// <summary>
/// 写Json
/// </summary>
public void WriteJson(string sex,int num,string selectType,string time)
{
ReadJson();
JsonDataItem data = new JsonDataItem();
data.Sex = sex;
data.Num = num;
data.SelectType = selectType;
data.Time = time;
if (root==null)
{
root = new Root();
root.JsonData = new List<JsonDataItem>();
root.JsonData.Add(data);
}
else
{
root.JsonData.Add(data);
}
string jsonStr = JsonMapper.ToJson(root);
if (!File.Exists(path))
{
File.Create(path).Dispose();
}
File.WriteAllText(path,jsonStr);
}
}
public class JsonDataItem
{
/// <summary>
/// 性别
/// </summary>
public string Sex { get; set; }
/// <summary>
/// 字数
/// </summary>
public int Num { get; set; }
/// <summary>
/// 风格
/// </summary>
public string SelectType { get; set; }
/// <summary>
/// 时间
/// </summary>
public string Time { get; set; }
}
public class Root
{
public List<JsonDataItem> JsonData = new List<JsonDataItem>();
}
读写Json(可以在unity用)
最新推荐文章于 2024-09-01 10:13:40 发布