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

如何在C#(Unity)中从JSON文件随机获取数据?[已解决]

Unity中Taboo类单词游戏的JSON数据随机访问方案

问题场景

开发类似Taboo的单词游戏时,需要从JSON文件中随机读取指定数据块(比如第二个数据块的核心词Computer和禁忌词Game、Work等),初始实现遇到了反序列化失败的问题。

初始错误的JSON格式

{"word":"Game",
   "tabooWords":[ "Ball", "Sport", "Computer",  "Phone", "Fun" ]
}
{
   "word":"Computer",
   "tabooWords":[ "Game", "Work", "Laptop", "PC", "Electronic" ]
}
{
   "word":"Software",
   "tabooWords":[ "Computer", "GitHub", "Developer", "İnsan", "Hikaye" ]
}

初始尝试的代码

[Serializable]
public class TabooData
{
    public string word;
    public List<string> tabuWords;

    public TabooData()
    {
        word = "";
        tabuWords = new();
    }
}
string path = Application.dataPath + "/DataSet/words.json";

if (File.Exists(path))
{
    string jsonString = File.ReadAllText(path);
    TabooData tabooWords = JsonConvert.DeserializeObject<TabooData>(jsonString);
}

问题原因

  1. JSON格式不合法:多个独立JSON对象直接并列,没有用数组[]包裹,不符合JSON语法规范,无法被反序列化为集合类型。
  2. 反序列化目标类型错误:代码中尝试将JSON反序列化为单个TabooData对象,但实际需要的是多个对象的集合。
  3. 属性名不匹配:类中属性名为tabuWords,但JSON中对应的键是tabooWords,拼写不一致会导致禁忌词无法被正确解析。

解决方案

修正后的JSON格式

将所有对象包裹在数组中,确保格式合法:

[
  {
    "word": "Game",
    "tabooWords": [ "Ball", "Sport", "Computer", "Phone", "Fun" ]
  },
  {
    "word": "Computer",
    "tabooWords": [ "Game", "Work", "Laptop", "PC", "Electronic" ]
  },
  {
    "word": "Software",
    "tabooWords": [ "Computer", "GitHub", "Developer", "Hacker", "Code" ]
  }
]

实现代码

调整类属性名匹配JSON键,将反序列化目标改为List<TabooData>,即可通过索引访问或随机获取数据:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class GameUIManager : MonoBehaviour
{
    public class TabooData
    {
        public string word { get; set; }
        public List<string> tabooWords { get; set; }
    }

    private void Start()
    {
        string path = Application.dataPath + "/DataSet/words.json";
        string jsonString = File.ReadAllText(path);
        var myWordsFromJson = JsonConvert.DeserializeObject<List<TabooData>>(jsonString);

        // 随机获取一个数据块
        int randomIndex = new System.Random().Next(myWordsFromJson.Count);

        // 通过索引访问核心词
        Debug.Log(myWordsFromJson[randomIndex].word);
        // 通过索引访问整个禁忌词列表
        Debug.Log(string.Join(", ", myWordsFromJson[randomIndex].tabooWords));
        // 通过索引访问禁忌词列表中的指定元素
        Debug.Log(myWordsFromJson[randomIndex].tabooWords[1]);
    }
}

访问说明

  • 通过myWordsFromJson[索引值]可以直接访问对应位置的数据块(比如myWordsFromJson[1]就是第二个数据块)。
  • 使用Random.Next()方法可以生成随机索引,实现随机抽取数据块的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 10:11:36