数据持久化(保存Json文件)---SimpleJson

本文介绍如何在Unity中使用SimpleJSON插件进行数据读写操作,包括设置和获取JSON数据的方法,并提供了具体的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using SimpleJSON;
using System.IO;
using System;
using GFW;
using System.Text;

public class GSetting {
    // json 文件
    static string _savePath = Application.dataPath + "/../WriteablePath/json/simple_json.json";

    public static void SetValue(string dataKey, object dataValue)
    {
        if (string.IsNullOrEmpty(dataKey))
        {
            Debug.Log(" is null !");
            return;
        }
        if (Refresh(dataKey, dataValue))
        {
            return;
        }
        JSONObject _newData = new JSONObject();
        _newData.Add(dataKey, Serialize(dataValue));
        if (_newData != null)
        {
            string sign = _newData.ToString() + "\r\n";
            GFileUtil.CreateDir(GFileUtil.GetDirPath(_savePath));
            File.AppendAllText(_savePath, sign, Encoding.UTF8);
            Debug.Log(" Save Success !");
        }
    }

    public static object GetValue(string dataKey, object dataValue = null)
    {
        if (GFileUtil.IsFileExists(_savePath))
        {
            try
            {
                StreamReader _readData = new StreamReader(_savePath);
                string _tempData = _readData.ReadLine();
                while (_tempData != null)
                {
                    var obj = JSONNode.Parse(_tempData);
                    JSONObject _jsonData = (JSONObject)obj;
                    JSONNode _tempValue = _jsonData[dataKey];
                    if (_tempValue != null)
                    {
                        //dataValue = _tempValue;
                        dataValue = Judge(_tempValue);
                        break;
                    }
                    _tempData = _readData.ReadLine();
                }
                _readData.Close();
            }
            catch (Exception e)
            {
                Debug.Log(e.ToString());
            }
        }
        return dataValue;
    }

    static object Judge(JSONNode jsonObj)
    {
        object obj = null;
        if (jsonObj != null)
        {
            if (jsonObj.Tag == JSONNodeType.Boolean)
            {
                obj = jsonObj.AsBool;
            }
            else if (jsonObj.Tag == JSONNodeType.Float)
            {
                obj = jsonObj.AsFloat;
            }
            else if (jsonObj.Tag == JSONNodeType.Int)
            {
                obj = jsonObj.AsInt;
            }
            else if (jsonObj.Tag == JSONNodeType.String)
            {
                obj = jsonObj.Value;
            }
        }
        return obj;
    }

    public static void SetUserData(string userId, string dataKey,object dataValue)
    {
        Type tt = dataValue.GetType();
        if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(dataKey))
        {
            Debug.Log(" null ");
            return;
        }
        if (Refresh(dataKey, dataValue,userId))
        {
            return;
        }
        JSONObject _parentData = new JSONObject();
        JSONObject _sonData = new JSONObject();
        _sonData.Add(dataKey, Serialize(dataValue));
        _parentData.Add(userId, _sonData);
        if (_parentData != null)
        {
            string sign = _parentData.ToString() + "\r\n";
            GFileUtil.CreateDir(GFileUtil.GetDirPath(_savePath));
            File.AppendAllText(_savePath, sign, Encoding.UTF8);
            Debug.Log(" Save Success !");
        }
    }

    public static object GetUserData(string userID, string dataKey, object dataValue = null)
    {
        if (GFileUtil.IsFileExists(_savePath))
        {
            try
            {
                StreamReader _readData = new StreamReader(_savePath);
                string _tempData = _readData.ReadLine();
                while (_tempData != null)
                {
                    JSONNode _jsonData = JSONNode.Parse(_tempData);
                    JSONNode _tempValue = _jsonData[userID]; 
                    if (_tempValue!=null)
                    {
                        JSONNode tempStr = _tempValue[dataKey];
                        if (tempStr != null)
                        {
                            //dataValue = tempStr;
                            dataValue = Judge(tempStr);
                            break;
                        }
                    }
                    _tempData = _readData.ReadLine();
                }
                _readData.Close();
            }
            catch (Exception e)
            {
                Debug.Log(e.ToString());
            }
        }
        return dataValue;
    }

    public static JSONNode Serialize(object dataValue)
    {
        JSONNode temp = null;
        if (dataValue != null)
        {
            Type valueType = dataValue.GetType();
            if (valueType == typeof(string))
            {
                temp = new JSONString(dataValue as string);
            }
            else if (valueType == typeof(bool))
            {
                temp = new JSONBool((bool)dataValue);
            }
            else if (valueType == typeof(float))
            {
                temp = new JSONFloat((float)dataValue);
            }
            else if (valueType == typeof(int))
            {
                temp = new JSONInt((int)dataValue);
            }
            else
            {
                Debug.LogError("unsupport type " + valueType.Name);
            }
        }
        return temp;
    }

    public static bool Refresh(string dataKey, object dataValue, string userID = null)
    {
        List<JSONObject> userConfigData = new List<JSONObject>();
        if (GFileUtil.IsFileExists(_savePath))
        {
            try
            {
                StreamReader _readData = new StreamReader(_savePath);
                string _tempData = _readData.ReadLine();
                while (_tempData != null)
                {
                    var obj = JSONNode.Parse(_tempData);
                    JSONObject _jsonData = (JSONObject)obj;
                    userConfigData.Add(_jsonData);
                    _tempData = _readData.ReadLine();
                }
                _readData.Close();
            }
            catch (Exception e)
            {
                Debug.Log(e.ToString());
            }
            bool isRepet = false;
            string _newContent = "";
            foreach (JSONObject item in userConfigData)
            {
                string tempStr = "";
                tempStr = item.ToString();
                if (userID != null)
                {
                    JSONNode _tempValue = item[userID];
                    if (_tempValue != null)
                    {
                        JSONNode _temp = _tempValue[dataKey];
                        if (_temp != null)
                        {
                            JSONObject _parentData = new JSONObject();
                            JSONObject _sonData = new JSONObject();
                            _sonData.Add(dataKey, Serialize(dataValue));
                            _parentData.Add(userID, _sonData);
                            tempStr = _parentData.ToString();
                            isRepet = true;
                        }
                    }
                }
                else
                {
                    JSONNode _tempValue = item[dataKey];
                    if (_tempValue != null)
                    {
                        JSONObject _refData = new JSONObject();
                        _refData.Add(dataKey, Serialize(dataValue));
                        tempStr = _refData.ToString();
                        isRepet = true;
                    }
                }
                _newContent += tempStr + "\r\n";
            }
            if (!string.IsNullOrEmpty(_newContent) && isRepet)
            {
                GFileUtil.CreateDir(GFileUtil.GetDirPath(_savePath));
                File.WriteAllText(_savePath, _newContent, Encoding.UTF8);
                Debug.Log(" Refresh Success !");
                return true;
            }
        }
        return false;
    }
}
要导入 SimpleJson 插件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值