camelMilk_
camelMilk_

Reputation: 41

Why is this JSON not being read correctly?

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.

Upvotes: 3

Views: 221

Answers (2)

Guru Stron
Guru Stron

Reputation: 142038

Your root json element is a json object which does not have countries property so you don't need the "root" object FirstNames, use Dictionary<string, FirstName> directly:

var firstNamesInJson = JsonUtility.FromJson<Dictionary<string, FirstName>>(jsonFile.text); 

P.S.

thanks to @derHugo in the comments - Unity built-in JsonUtility does not support the Dictionary deserialization ATM (docs), so you will need to use 3rd party library for such dynamic deserialization with Dictionary (for example Newtonsoft.Json)

Upvotes: 3

derHugo
derHugo

Reputation: 90659

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 a root.

see Deserialize a Dictionary

void Start(){
    var firstNamesInJson = JsonConvert.DeserializeObject<Dictionary<string, FirstName>>(jsonFile.text); 
    Debug.Log("Found name: " + firstNamesInJson.countries["India"].male[0]); 
} 

Upvotes: 2

Related Questions