JsonUtility is returning null

For some reason, the JsonUtilities.FromJson is no longer working. This just happened after I created a new scene that relates to nothing to either the json file nor really any other object. The strangest thing is that everthing is proper, at least from what I can tell. Can someone please help, here’s the code:
(Game manager)

public void LoadData() {
        if( File.Exists(dataPath) ) {
            string jsonFileData = File.ReadAllText( dataPath );
            print( jsonFileData );
            if( jsonFileData.Equals( "" ) ) {
                return;
            }
            Settings colorSettings = JsonUtility.FromJson<Settings>( jsonFileData );
            for(int i = 0; i < colorSettings.items.Length; i++ ) {//NullPointerException is thrown from here cause by the above statement.
                Color tempColor = new Color();
                if( !ColorUtility.TryParseHtmlString( colorSettings.items[i].value, out tempColor ) ) {
                    throw new System.Exception( "Unable to parse hex to color." );
                }
                colorPref.Add( colorSettings.items[i].key, tempColor );
            }
        }
    }
[System.Serializable]
public class Settings {
    public SettingsItem[] items;
}
[System.Serializable]
public class SettingsItem {
    public string key, value;
}

If your null is being thrown in your for statement, then that means either colorSettings or items is null. (assuming the line you pointed to is what the error points to).

I don’t use JsonUtility myself, but my guess is if it’s not properly setting the value, then it may end up null because it can’t convert the string into the class properly.

What is jsonFileData printing out? Is it still correctly formatted?

It prints: {“BodyColor”:“ffff71”,“OutterColor”:“ffffff”,“BoarderColor”:“ffffff”} the console shows:
{“BodyColor”:“ffff71”,“OutterColor”:“ffffff”,“BoarderColor”:“ffffff”}
UnityEngine.MonoBehaviour: print(Object)
GameManager:LoadData() (at Assets/Scripts/Core Game/GameManager.cs:74)
GameManager:Awake() (at Assets/Scripts/Core Game/GameManager.cs:19)
The format shown is how JsonUtilities writes it.

Your json formatting is incorrect. You can toss that json string into json2csharp and it gives you what you get back.

A quick test in creating the object and then doing a ToJson prints out this

{“items”:[{“key”:“BodyColor”,“value”:“ffff71”},{“key”:“OuterColor”,“value”:“ffffff”},{“key”:“BoarderColor”,“value”:“ffffff”}]}

That is why you are getting null.

So when I save the things I need to a json, do I have to pipe it into the Settings Data class in order for it to save like that or into a diction or what?

You’ll use JsonUtilities.ToJson(colorSettings). Or whatever your settings variable will be.

If you’re converting the values from settings into a dictionary, you have to convert the dictionary back into settings.

Okay cool, thanks. I’m still new to Unity so yeah, thanks for the help. :smile: