Home > database >  Is there any way to get random data from a json file in C#?
Is there any way to get random data from a json file in C#?

Time:12-01

I make a Taboo-like word game using Unity game engine. I want to randomly access words in json. Is there any way to access with indexes, like myWords[2] ? Or another way? My json is like this:

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

I tried:

[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);
}

I don't know what is wrong and what to do next.

CodePudding user response:

The first thing is to make sure your JSON is valid (which it isn't). It should be an array ([]) and needs a comma between each section.

Then you need to deserialise it, and then after choosing a section, select a random taboo word.

Here's a working fiddle that just accesses the "Game" taboo words: https://dotnetfiddle.net/2ugmtZ

using System;
using System.Text.Json.Serialization;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public class Item
    {
        public string word {get;set;}
        public List<string> tabooWords {get;set;}
    }
    
    public static void Main()
    {
        const string input = @"
        [{
   ""word"":""Game"",
   ""tabooWords"":[ ""Ball"", ""Sport"", ""Computer"",  ""Phone"", ""Fun"" ]
},
{
   ""word"":""Computer"",
   ""tabooWords"":[ ""Game"", ""Work"", ""Laptop"", ""PC"", ""Electronic"" ]
},
{
   ""word"":""Software"",
   ""tabooWords"":[ ""Computer"", ""GitHub"", ""Developer"", ""İnsan"", ""Hikaye"" ]
}]";
        
        var d = System.Text.Json.JsonSerializer.Deserialize<List<Item>>(input);
        var words = d.First(x=>x.word == "Game");

        Console.WriteLine(words.tabooWords.ElementAt(new Random().Next(words.tabooWords.Count())));
    }
}

CodePudding user response:

You need to create a class for your object, then use Random to get a random word.

public class TabooGame
{
    [JsonProperty("word")]
    public string Word { get; set; }
    [JsonProperty("tabooWords")]
    public string[] TabooWords { get; set; }
}

public class Game
{
    public string GetRandomWords(string jsonString)
    {
        var taboo = JsonConvert.DeserializeObject<TabooGame>(jsonString);
        var wordCount = taboo.TabooWords.Count();

        var randomIndex = new Random().Next(0, wordCount - 1);

        return taboo.TabooWords[randomIndex];
    }
}
  • Related