Home > Net >  Is there any way to get random data from a json file in C#? [solved]
Is there any way to get random data from a json file in C#? [solved]

Time:12-02

I make a Taboo-like word game using Unity game engine. I want to randomly access blocks in json. For example, load words in second block (Computer, Game, Work ...). Is there any way to access with indexes? Or another way? My json is like this:
(Scroll down for solution)

{
   "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.

Update: I tried after replies and I did. I phrased my question more clearly. Thanks for the responses.
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" ]
  }
]

The code:

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

        Console.WriteLine(myWordsFromJson[randomIndex].word); // Access the word
        Console.WriteLine(myWordsFromJson[randomIndex].tabooWords); // Access tabooWords
        Console.WriteLine(myWordsFromJson[randomIndex].tabooWords[1]); // Access tabooWords at any index
    }
}

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