I have a large list of names in JSON arranged by country and sorted into male and female. I would like to be able to access these names within unity to apply them to various generated game characters etc. When trying to do this I am receiving a Null reference error but am out of ideas on how to approach/ fix it.
I have tried creating a Dictionary to access the names. Here is an example of the JSON:
//json example
{
"India":{
"male":[
"A_Jay",
"Aaban",
"Aabid",
"Aabir",
"Aadam"
],
"female":[
"A_Jay",
"Aaban",
"Aabid",
"Aabir",
"Aadam"
]
},
"Usa":{
"male":[
"A_Jay",
"Aaban",
"Aabid",
"Aabir",
"Aadam"
],
"female":[
"A_Jay",
"Aaban",
"Aabid",
"Aabir",
"Aadam"
]
}
}
Here is my attempt at reading the json file:
//jsonreader.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FirstName {
public List<string> male;
public List<string> female;
}
public class FirstNames {
public Dictionary<string, FirstName> countries;
}
public class JSONReader : MonoBehaviour {
public TextAsset jsonFile;
void Start(){
FirstNames firstNamesInJson = JsonUtility.FromJson<FirstNames>(jsonFile.text);
Debug.Log("Found name: " + firstNamesInJson.countries["India"].male[0]);
}
}
My Debug Log is returning a Null reference error and I’m not sure why.
2
Answers
Your root json element is a json object which does not have
countries
property so you don’t need the "root" objectFirstNames
, useDictionary<string, FirstName>
directly:P.S.
thanks to @derHugo in the comments – Unity built-in
JsonUtility
does not support theDictionary
deserialization ATM (docs), so you will need to use 3rd party library for such dynamic deserialization withDictionary
(for exampleNewtonsoft.Json
)Unity built-in
JsonUtility
uses the normal Unity serialization rules ..Dictionary
is not supported by it… the main answer is:You will need a third-party JSON library in the first place!
Like e.g.
Newtonsoft JSON.Net
(it comes as a package) and then as was mentioned before your JSON doesn’t have aroot
.see Deserialize a Dictionary