So I’m trying to read this JSON file into a string[ ] in unity:
{
"Usernames": [
"stadiumhoop",
"tugofwarvalley",
"slalompath",
"binnacleluge",
"tennisprecious",
"mattidings",
"dugoutdeep",
"icelandbaseball",
"polevaultportrait"
]
}
The actual username list is much larger.
The code I’m using to read it is the following:
public TextAsset usernameDB;
private void Start()
{
string[] allUsernames = JsonUtility.FromJson<string[]>(usernameDB.text);
Debug.Log(allUsernames.Length);
}
The Debug.Log returns 0, meaning the string[ ] is empty.
How can I read this file correctly?
Thanks in advance.
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).
Also, always be sure to leverage sites like:
JSONLint is the free online validator, json formatter, and json beautifier tool for JSON, a lightweight data-interchange format. You can format json, validate json, with a quick and easy copy+paste.
https://csharp2json.io
If you have a class or struct that contains a public string[ ] Usernames field it should deserialize.
public class Data
{
public string[] Usernames;
}
Then call:
var data = JsonUtility.FromJson(…);
1 Like
CodeSmile:
If you have a class or struct that contains a public string[ ] Usernames field it should deserialize.
public class Data
{
public string[] Usernames;
}
Then call:
var data = JsonUtility.FromJson(…);
Thanks! This worked perfectly!