According this this answer, JsonUtility only supports simple types, and that excludes dictionaries (this is explicitly mentioned in the answer).

Your best bet would be to switch to Json.NET, which is available as a NuGet package, which supports more complex use cases such as this one.

Answer from Vera on Stack Overflow
Top answer
1 of 2
5

According this this answer, JsonUtility only supports simple types, and that excludes dictionaries (this is explicitly mentioned in the answer).

Your best bet would be to switch to Json.NET, which is available as a NuGet package, which supports more complex use cases such as this one.

2 of 2
1

Use the following code :

 static string ConvertFooClassToJson()
    {
        List<string> jsonStrings = new List<string>();
        foreach (FieldInfo field in typeof(Foo).GetFields())
        {
            string fieldName = field.Name;
            Foo fieldsInstant = new Foo();
            var fieldValue = field.GetValue(fieldsInstant);
            if (field.FieldType.IsValueType)
            {
                string valueType = $"{fieldName}:{fieldValue}";
                jsonStrings.Add(valueType);
            }
            else
            {
                dynamic dynamicDic = fieldValue;
                List<string> dicValues = new List<string>();

                foreach (var dicItem in dynamicDic)
                {
                    var itemKey = dicItem.Key;
                    var itemValue = dicItem.Value;

                    List<string> barClassLst = new List<string>();
                    Bar barValue = itemValue;
                    foreach (var barItem in barValue.GetType().GetProperties())
                    {
                        var barPropertyName = barItem.Name;
                        var barPropertyValue = barItem.GetValue(barValue);
                        barClassLst.Add($"{barPropertyName}:{barPropertyValue}");
                    }

                    var barPropertiesString = "{" + string.Join(',', barClassLst.ToArray()) + "}";

                    string dicString = $"{itemKey}:{barPropertiesString}";
                    dicValues.Add(dicString);
                }
                var fooString = "{" + string.Join(',', dicValues.ToArray()) + "}";
                string finalString = $"{fieldName}:{fooString}";
                jsonStrings.Add(finalString);
            }
        }
        string jsonResult = "{" + string.Join(',', jsonStrings.ToArray()) + "}";
        return jsonResult;
    }
🌐
Unity
discussions.unity.com › questions & answers
How can I save a Dictionary in a class to JSON? - Questions & Answers - Unity Discussions
May 13, 2016 - I’m trying to save some data to JSON. I have a class that is being saved and it contains a Dictionary. My class looks as such: [Serializable] public class Level { public string id; public int width; public int depth; public Dictionary otherColums = new Dictionary (); } and is contained within another class: [Serializable] public class LevelArray { public Level level; } There will eventually be multiple levels to be loaded, but for now I just have the ...
Discussions

string Dictionary to JSON?
Right, serializing Dictionaries needs a workaround. E.g. serializing an array with a struct that contains two strings, or just sterilizing all keys and values in some specific order (key, value, key, value... for example). The struct feels nicer I guess since it would work with any pairs of key and value types. More on reddit.com
🌐 r/Unity3D
4
2
March 22, 2023
Need help serializing a Dictionary<string, object> using Json
Hello, I’m using an asset save system and it works, however I’m trying to mess with it and things start to go wrong. Right now I’m trying to switch from BinaryFormatter to Json. As I understand the base of the system is a Dictionary which stores pretty much everything; here’s how a ... More on discussions.unity.com
🌐 discussions.unity.com
1
0
February 4, 2025
c# - Unity Serializing Nested Dictionary to JSON - Stack Overflow
The REST service I am using, RSA Archer, is expecting an integer key which means I simply can't nest [Serializable] objects and then JsonUtility.ToJson() to create the serialized JSON string. I tho... More on stackoverflow.com
🌐 stackoverflow.com
How can I save a Dictionary in a class to JSON? - Questions & Answers - Unity Discussions
I’m trying to save some data to JSON. I have a class that is being saved and it contains a Dictionary. My class looks as such: [Serializable] public class Level { public string id; public int width; public int depth… More on answers.unity.com
🌐 answers.unity.com
0
May 12, 2016
🌐
Unity
discussions.unity.com › unity engine
JsonUtility can't serialize Dictionary - Unity Engine - Unity Discussions
March 22, 2021 - Why, Unity? Like… it’s a dictionary!! It’s literally a json! I’d understand if I was asking something vastly complicated and you were like “nah, dude, too hard”. But it’s a dictionary! Why can’t you just loop over keys and shove them into a string???
🌐
Reddit
reddit.com › r/unity3d › string dictionary to json?
r/Unity3D on Reddit: string Dictionary to JSON?
March 22, 2023 -

I'm trying to figure out the easiest way to get a Dictionary<string, string> to a JSON array string format, so that for example:

 Dictionary<string, string> myDict = new Dictionary<string, string>()
 myDict.Add("name", "john");
 myDict.Add("age", "21");

is converted to

  [ 
      "name" : "john",
      "age" :  "21"
  ]

and so on.

I can't seem to fine a NewtonSoft.JSON (included in Unity) call that will do that.

Is it easier to just iterate over the dictionary and build that string manually?

🌐
Rwth-acis
rwth-acis.github.io › i5-Toolkit-for-Unity › 1.6.0 › manual › Utilities › Json-Dictionary-Utility.html
Json Dictionary Utility | i5 Toolkit Documentation
To serialize an array to JSON, call ToJson. It returns a JSON object with two arrays "keys" and "values". These arrays are the contents of the array entries. Dictionary<string, int> dictionary = new Dictionary<string, int>(); dictionary.Add("firstKey", 42); dictionary.Add("secondKey", 1); string ...
Find elsewhere
🌐
Reddit
reddit.com › r/unity3d › how to serialize a dictionary with "object" as value in unity, to json
r/Unity3D on Reddit: How to Serialize a Dictionary with "Object" as value in Unity, to JSON
November 28, 2021 - Spent soooo long on this after realising the custom Get/Set Pref in my Save System didn't work. It was able to contain any kind of data until I tried to store a Dictionary<string, object> Turns out JsonUtility doesn't work with complex data types very well. I was pointed towards Newtonsoft Json.NET but even that struggled.
🌐
Reddit
reddit.com › r/unity3d › how to save list to json file
r/Unity3D on Reddit: How to save List< Dictionary< string, string [] > > to json file
March 23, 2020 -

Trying to save one List< Dictionary< string, string [] > > and then load them when the program start.

Current kode for saving:

string json = JsonUtility.ToJson(DATA.CommandList);

File.WriteAllText(Application.persistentDataPath+FileName, json);

Will end up with a file that contains:

{ }

🌐
Unity
forum.unity.com › unity engine
Dictionary support (or workaround) for JsonUtility (test case included) - Unity Engine - Unity Discussions
January 13, 2016 - For example, is there any way to parse this structure? (NOTE: Title field being dynamic and not a 3 fixed value structure) { "id": 1, "title": { "es": "1", "en": "2", "fr": "3" } } public class Test { public int id; public Dictionary title; } https://feedback.unity3d.com/suggestions/support-conversion-of-json...
🌐
GitHub
gist.github.com › kankikuchi › f7191439a47d26cf9e6f
Dictionary⇔JSON【Unity】
Save kankikuchi/f7191439a47d26cf9e6f to your computer and use it in GitHub Desktop. Download ZIP · Dictionary⇔JSON【Unity】 · Raw · JsonSerializer.cs · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below.
🌐
Unity
discussions.unity.com › unity engine
json string to dictionary - Unity Engine - Unity Discussions
April 13, 2020 - I have a simple json string {“1”:10,“2”:25,“3”:1,“4”:124,“7”:567} I have a Dictionary Dictionary Gameitems = new Dictionary (); What is the best way to get the json string into the dictionary? Is there a simple json parser that will do it or will i have to parse the json ...
🌐
Unity
docs.unity3d.com › 2020.1 › Documentation › Manual › JSONSerialization.html
Unity - Manual: JSON Serialization
The JSON Serializer API supports any MonoBehaviour subclass, ScriptableObject subclass, or plain class or struct with the [Serializable] attribute. When you pass in an object to the standard Unity serializer for processing, the same rules and limitations apply as they do in the Inspector: Unity serializes fields only; and types like Dictionary<> are not supported.
🌐
Unity
discussions.unity.com › unity engine
JsonUtility.FromJson is empty for simple dictionary??? - Unity Engine - Unity Discussions
December 31, 2018 - I have simple json data: {"key_one": ... SimpleJsonData { public string name; public float val; } void Start() { string jsonPath = "c:/pat_to_json/file.json"; Dictionary simpleJson = null; if (File.Exists (jsonPath)) { string jsonTxt = File.ReadAl......
🌐
Medium
medium.com › @defuncart › json-serialization-in-unity-9420abbce30b
JSON Serialization in Unity. Get up to speed with JSON Serialization… | by James Leahy | Medium
June 13, 2017 - JSON is a human-readable and ... supports serializable classes but is somewhat limited in that 1) it does not support dictionaries or top level arrays, and 2) all properties must be public....