读写Json(可以在unity用)

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>();
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值