You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中如何以日期为索引将多组字符串列表保存为JSON文件

按日期分组存储JSON数据的Unity实现方案

我来帮你搞定这个按日期分组存储数据的需求~你之前的问题核心是没法把日期作为JSON的键来分组,其实Unity的JsonUtility(2020及以上版本)已经支持Dictionary的序列化了,刚好可以用它来实现你想要的结构。

问题回顾

你需要将三个字符串列表(names、location、info)按日期分组保存,后续能通过日期快速查询并执行增删操作,但之前用List的类结构没法实现日期作为键的分组效果。

期望的JSON结构

你想要的结构应该是这样的(日期作为键,每个日期对应三个列表):

{
  "entries": {
    "20-05-2024": {
      "names": ["张三", "李四"],
      "location": ["办公室", "会议室"],
      "info": ["项目讨论", "进度汇报"]
    },
    "21-05-2024": {
      "names": ["王五"],
      "location": ["实验室"],
      "info": ["测试新功能"]
    }
  }
}

解决方案:调整类结构使用Dictionary

我们可以用Dictionary<string, DailyEntries>来存储,其中字符串键就是日期,DailyEntries包含你需要的三个列表。

1. 定义可序列化的类

using System.Collections.Generic;
using UnityEngine;

[Serializable]
public class DailyEntries
{
    // 对应三个字符串列表
    public List<string> names = new List<string>();
    public List<string> location = new List<string>();
    public List<string> info = new List<string>();
}

[Serializable]
public class JournalData
{
    // 用日期字符串作为键,对应当天的所有条目
    public Dictionary<string, DailyEntries> entries = new Dictionary<string, DailyEntries>();
}

2. 保存数据的代码(支持新增/更新)

这段代码会先读取已有的JSON(如果存在),然后检查当前日期的条目,不存在就创建,之后添加数据再保存:

using System.IO;
using UnityEngine;

public class JournalSaver : MonoBehaviour
{
    public void SaveJournalData(string newName, string newLocation, string newInfo)
    {
        string savePath = Path.Combine(Application.persistentDataPath, "Journal.json");
        JournalData journalData = new JournalData();

        // 读取已存在的数据(如果文件存在)
        if (File.Exists(savePath))
        {
            string existingJson = File.ReadAllText(savePath);
            journalData = JsonUtility.FromJson<JournalData>(existingJson);
        }

        // 获取当前日期(只保留日期部分,格式统一为"dd-MM-yyyy")
        string currentDate = DateTime.UtcNow.ToLocalTime().ToString("dd-MM-yyyy");

        // 如果当前日期没有条目,创建新的
        if (!journalData.entries.ContainsKey(currentDate))
        {
            journalData.entries[currentDate] = new DailyEntries();
        }

        // 向对应日期的列表添加新数据
        journalData.entries[currentDate].names.Add(newName);
        journalData.entries[currentDate].location.Add(newLocation);
        journalData.entries[currentDate].info.Add(newInfo);

        // 序列化并保存(prettyPrint: true让JSON格式更易读)
        string json = JsonUtility.ToJson(journalData, prettyPrint: true);
        try
        {
            File.WriteAllText(savePath, json);
            Debug.Log("数据保存成功!路径:" + savePath);
        }
        catch (System.Exception e)
        {
            Debug.LogError("保存数据出错:" + e.Message);
        }
    }
}

3. 查询并修改数据的代码

比如根据指定日期查询,然后执行增删操作:

public void ModifyJournalData(string targetDate)
{
    string savePath = Path.Combine(Application.persistentDataPath, "Journal.json");
    if (!File.Exists(savePath))
    {
        Debug.LogWarning("未找到保存文件!");
        return;
    }

    // 读取数据
    string json = File.ReadAllText(savePath);
    JournalData journalData = JsonUtility.FromJson<JournalData>(json);

    // 查询目标日期的条目
    if (journalData.entries.TryGetValue(targetDate, out DailyEntries dailyData))
    {
        // 示例:删除第一个名字
        if (dailyData.names.Count > 0)
        {
            dailyData.names.RemoveAt(0);
            Debug.Log("已删除目标日期的第一个名字");
        }

        // 示例:新增一条信息
        dailyData.info.Add("新增的日志信息");

        // 保存修改后的数据
        string updatedJson = JsonUtility.ToJson(journalData, prettyPrint: true);
        File.WriteAllText(savePath, updatedJson);
        Debug.Log("数据修改并保存成功!");
    }
    else
    {
        Debug.LogWarning("未找到日期:" + targetDate);
    }
}

注意事项

  • 如果你的Unity版本低于2020,JsonUtility不支持直接序列化Dictionary,这时候可以选择安装Newtonsoft.Json for Unity(在Package Manager里搜索即可),它对字典的支持更完善。
  • 日期格式要保持统一(比如都用dd-MM-yyyy),避免因为格式不一致导致查询不到数据。

内容的提问来源于stack exchange,提问作者stratos la

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 04:57:38