Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Reading a string array from a JSON file

Discussion in 'Scripting' started by FedesaXD, Aug 12, 2023.

  1. FedesaXD

    FedesaXD

    Joined:
    Apr 13, 2023
    Posts:
    4
    So I'm trying to read this JSON file into a string[] in unity:

    Code (CSharp):
    1. {
    2.     "Usernames": [
    3.         "stadiumhoop",
    4.         "tugofwarvalley",
    5.         "slalompath",
    6.         "binnacleluge",
    7.         "tennisprecious",
    8.         "mattidings",
    9.         "dugoutdeep",
    10.         "icelandbaseball",
    11.         "polevaultportrait"
    12.     ]
    13. }
    The actual username list is much larger.
    The code I'm using to read it is the following:

    Code (CSharp):
    1. public TextAsset usernameDB;
    2.  
    3.     private void Start()
    4.     {
    5.         string[] allUsernames = JsonUtility.FromJson<string[]>(usernameDB.text);
    6.         Debug.Log(allUsernames.Length);
    7.     }
    The Debug.Log returns 0, meaning the string[] is empty.
    How can I read this file correctly?
    Thanks in advance.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    Problems with Unity "tiny lite" built-in JSON:

    In general I highly suggest staying away from Unity's JSON "tiny lite" package. It's really not very capable at all and will silently fail on very common data structures, such as bare arrays, tuples, Dictionaries and Hashes and ALL properties.

    Instead grab Newtonsoft JSON .NET off the asset store for free, or else install it from the Unity Package Manager (Window -> Package Manager).

    https://assetstore.unity.com/packages/tools/input-management/json-net-for-unity-11347

    Also, always be sure to leverage sites like:

    https://jsonlint.com
    https://json2csharp.com
    https://csharp2json.io
     
  3. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    3,899
    If you have a class or struct that contains a public string[] Usernames field it should deserialize.
    Code (CSharp):
    1. public class Data
    2. {
    3.     public string[] Usernames;
    4. }
    Then call:
    var data = JsonUtility.FromJson<Data>(..);
     
    FedesaXD likes this.
  4. FedesaXD

    FedesaXD

    Joined:
    Apr 13, 2023
    Posts:
    4
    Thanks! This worked perfectly!