JsonUtility.ToJson produces blank JSON even for int data

I am trying to build a simple system for saving my game state to a JSON file, but I keep getting blank JSON. I have read many posts on this forum and on Stack Overflow from people with similar issues, but in all of the issues I have seen, the issue boiled down to the player trying to serialize a complex type (e.g. a Dictionary) that Unity’s JsonUtility cannot serialize. But I am getting blank JSON even with primitive types, e.g. integers.

Here is a minimal example:

1. Create an empty 3D project and generate two C# scripts as follows:

GameData.cs, a class for holding the data:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class GameData
{
    public int score { get; set; }
    public int health { get; set; }

    public GameData(int score, int health)
    {
        this.score = score;
        this.health = health;
    }
}

SaveLoadManager.cs, which will write the JSON to a file (in this case, we just write to the console to keep things simple):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SaveLoadManager : MonoBehaviour
{
    void OnMouseDown()
    {
        SaveJson();
    }

    void SaveJson()
    {
        var data = new GameData(4, 5);
        var serializedData = JsonUtility.ToJson(data);
        Debug.Log($"Serialized data: {serializedData}");
    }
}

2. Create an empty cube and add the SaveLoadManager.cs script to it.

3. Play the game and click on the cube. The following is logged to the console:

8725350--1180146--upload_2023-1-12_11-40-5.png

(“Serialized data: {}”)

Why is my JSON empty?

(Unity v2021.3.16f1 on Windows 10.)

1 Like

JsonUtility doesn’t serialize properties, only fields that are either public or have the SerializeField attribute.

You can tell it to serialize a property’s backing field by using [field: SerializeField] but it’ll be called something like <score>k__BackingField in the result.

3 Likes

I always use Json.net myself, but one thing I noticed is JsonUtility seems to use fields and not properties. I don’t know if there is a difference, but I suggest giving it a try and see if it makes a difference or not.

Thank you, I had also read about this issue but got the concepts of fields and properties reversed in my head.