2

Having a structure for nested json file as nested classes, when I write into json, always the json is empty.

public class Class1
{
    public int level;
    public float timeElapsed;
    public string playerName;
    public Class2 subClass;


}

public class Class2
{
    public int age;
}

Class2 class2= new Class2();
class2.age = 99;

Class1 myObject = new Class1();
myObject.level = 1;
myObject.timeElapsed = 47.5f;
myObject.playerName = "Francis";
myObject.subClass = class2;

jsonString = JsonUtility.ToJson(myObject);
print(jsonString);

I am getting {"level":1,"timeElapsed":47.5,"playerName":"Francis"}, where is the age ?!

1
  • 4
    I don't do Unity, but I found this which suggests you need the [Serializable] attribute on your classes. Commented Aug 6, 2019 at 1:42

1 Answer 1

1
using System;
using UnityEngine;

public class Example : MonoBehaviour
{
    private void Start()
    {
        Class2 class2 = new Class2();
        class2.age = 99;

        Class1 myObject = new Class1();
        myObject.level = 1;
        myObject.timeElapsed = 47.5f;
        myObject.playerName = "Francis";
        myObject.subClass = class2;

        var jsonString = JsonUtility.ToJson(myObject);
        print(jsonString);
    }
}

[Serializable]
public class Class1
{
    public int level;
    public float timeElapsed;
    public string playerName;
    public Class2 subClass;
}

[Serializable]
public class Class2
{
    public int age;
}

The result is {"level":1,"timeElapsed":47.5,"playerName":"Francis","subClass":{"age":99}}

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.