CodeBlanks Logo Icon CodeBlanks

Challenge 3: Save JSON

Write a script that serializes a class with JsonUtility.ToJson.

Challenge 3: JSON Save System

To persist gameplay progression, data models tagged with [System.Serializable] are used. Calling JsonUtility.ToJson(data) serializes the object directly into a JSON string.

[System.Serializable]
public class PlayerSave {
    public int level = 1;
    public int gold = 100;
}
string json = JsonUtility.ToJson(new PlayerSave());

The serialized payload is written to a file under Application.persistentDataPath for robust cross-platform storage.

Practice JSON save data test

Define a Start method. Inside, declare string kayitMetni = "Seviye: 10, Altin: 250"; and print "Kayit verisi: " + kayitMetni to the console.

Starter code

Player.cs
using UnityEngine;

public class JsonSaveTester : MonoBehaviour
{
    // Start icinde kayitMetni tanimla ve yazdir
}

Sample solution

Player.cs
using UnityEngine;

public class JsonSaveTester : MonoBehaviour
{
    void Start()
    {
        string kayitMetni = "Seviye: 10, Altin: 250";
        Debug.Log("Kayit verisi: " + kayitMetni);
    }
}

Expected output

Kayit verisi: Seviye: 10, Altin: 250

Practice Save version check

Define a Start method. Inside, declare int kayitSurumu = 3; and print "Kayit surumu: " + kayitSurumu to the console.

Starter code

Player.cs
using UnityEngine;

public class SaveVersionTester : MonoBehaviour
{
    // Start icinde kayitSurumu tanimla ve yazdir
}

Sample solution

Player.cs
using UnityEngine;

public class SaveVersionTester : MonoBehaviour
{
    void Start()
    {
        int kayitSurumu = 3;
        Debug.Log("Kayit surumu: " + kayitSurumu);
    }
}

Expected output

Kayit surumu: 3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which attribute must be placed above a class definition for it to be serialized into JSON text by JsonUtility?

  • [DisallowMultipleComponent]
  • [System.Serializable] Correct answer
  • [HideInInspector]
  • [ExecuteAlways]

Explanation: The [System.Serializable] attribute enables Unity to inspect class fields and serialize them into JSON.

2 Serialize object to JSON text

Question
string jsonString = JsonUtility.____(gameSave);
Answer
string jsonString = JsonUtility.ToJson(gameSave);

Explanation: The 'JsonUtility.ToJson' method is called to convert an object into JSON string format.

3 Save mechanism concepts

Term Meaning
JsonUtility.ToJson Serializes object into JSON text
JsonUtility.FromJson Deserializes JSON text into an object
[System.Serializable] Attribute enabling class serialization
persistentDataPath Safe platform path for saving files

All lessons in Advanced