1

I have these two classes:

public class MyParent
{
    public string a;

    public MySub[] b;
}

public class MySub
{
    public int sub;
}

I initialize them like this:

myPC = new MyParent();
myPC.a = "test";
myPC.b = new MySub[2];

myPC.b[0] = new MySub();
myPC.b[1] = new MySub();

myPC.b[0].sub = 1;
myPC.b[2].sub = 2;

But when I serialize the object, The result is only {"a":"test"}

string json = JsonUtility.ToJson(myPC);
Debug.Log(json); // {"a":"test"}

How do I do that correctly and convert JSON back to an object?

Dayan
  • 7,634
  • 11
  • 49
  • 76
DeLe
  • 2,442
  • 19
  • 88
  • 133

1 Answers1

1

Internally, JsonUtility uses the Unity Serializer; therefore the object you pass in must be supported by the serializer: it must be a MonoBehaviour, ScriptableObject, or plain class/struct with the Serializable attribute applied.

To ensure a custom class can be serialized, it needs the Serializable attribute and must follow these rules:

  1. Is not abstract
  2. Is not static
  3. Is not generic, though it may inherit from a generic class

Change your custom class to this:

[System.Serializable]
public class MyParent
{
    public string a;
    public MySub[] b;
}

[System.Serializable]
public class MySub
{
    public int sub;
}

For more in-depth information on Script Serialization, check the official documentation: https://docs.unity3d.com/Manual/script-Serialization.html

Dayan
  • 7,634
  • 11
  • 49
  • 76