Json File Written Empty

Using the below code, the Json file written is completely empty (except for 2 curly brackets; “{}”).

void SaveData()
    {
        //Create Output from list of PrefabData
        StringBuilder sb = new StringBuilder();
        string outputData = "";

        foreach (PrefabData prefabDataItem in prefabData)
        {
            sb.Append(prefabDataItem.CategoryName);
            sb.Append(",");
            foreach (string gameObjectRef in prefabDataItem.GameObjectRefs)
            {
                sb.Append(gameObjectRef);
                sb.Append(",");
            }
            sb.Append("#");//end of category marker
        }
        outputData = sb.ToString();
        //EditorPrefs.SetString("Prefab_Library_SaveData", outputData);
        Debug.Log(outputData);
        string jsonData = JsonUtility.ToJson(outputData, true);
        File.WriteAllText(Application.persistentDataPath + "/PrefabLibrarySaveData.json", jsonData);
    }

This code should get a result of this for example:

A,CategoryItem1,CategoryItem2,#B,CategoryItem1,CategoryItem2,#

And this is what is written to the console, but when going to see the file (opening it in Notepad) the file is blank apart from “{}”.

What exactly am I doing wrong here? Can Json not save data like this or have I just done something wrong?

JsonUtility.ToJson() serializes the public fields of some object. I’m not really sure of what all the implications are of trying to serialize a string as an object into a JSON, but this isn’t how this method was intended to be used (String has no serializable public fields, as most primitives).

For example, you could probably serialize the contents of a PrefabData object, but since it looks like you want a particular field from a bunch of them, you could instead write a class SomeClass designed to hold those values, instance one in the above script and assign all of the CategoryName’s to its fields, then serialize that.

Something like:

//Assuming SomeClass is already defined...

SomeClass aboutToBeSerialized;

foreach (PrefabData prefabDataItem in prefabData)
{
    //assign the CategoryName to a field in aboutToBeSerialized
}

//...

string jsonData = JsonUtility.ToJson(aboutToBeSerialized, true);

//...

Arrays should be supported by JsonUtility as long as they’re in a class/struct, so you could use that as a public member in your class to store the variable length of data.