[SOLVED] JSON Serialization of Derived Classes

Hello all. I am trying to serialize a list of results into a JSON string. I have a base class for all of my results, and have a few derived classes that add additional data members. I was looking at the JSON string and only saw that the base class data members were being written to the file.

[System.Serializable]
public class BaseResult {
    public string name;
    public enum ResultType {
        None,
        Accepted,
        Denied
    };
    public ResultType type;

    public BaseResult(){
        name = "base";
        type = ResultType.None;
    }
}

[System.Serializable]
public DerivedResultA : BaseResult {
    public int input;

    public DerivedResultA() : base() {
        name = "derivedResult";
        input = 0;
    }
}

[System.Serializable]
public GameResults {
    public List<BaseResults> results;
    public GameResults(){
        results = new List<BaseResult>();
    }
    public Add(BaseResult b){
        results.Add(b);
    }
}

private GameResults g_results;

void Start() {
    for(int i = 0; i < 10; i++) {
        g_results.results.Add(new DerivedResultA());
    }

    string jsonOut = JSONUtility.ToJson(results);

    Debug.Log(jsonOut);
}

Would output the following JSON:

{
    "results":
    [
        {
            "name" : "derivedResult",
            "type" : 0
        },
        ...
        {
            "name" : "derivedResult",
            "type" : 0
        }
    ]
}

Will I have to parse the results collection and have a switch statement to cast the list member as the derived class to get the data members of the derived class serialized?

It seems that Unity’s Json Serialization is sub-par. I will have to make some very hacky conditionals and loops to have the Json Serializer actually serialize the data I have.

Example method:

string HackyToJson(GameResults gr)
{
    string resultsJson = "";
    resultsJson += "{\"results\":[";
    for (int i = 0; i < gr.results.Count; i++)
    {
        if (gr.results*.name == "derivedResultA")*

{
resultsJson += JsonUtility.ToJson(((DerivedResultA)gr.results*));*
}
if (i < gr.results.Count - 1)
{
resultsJson += “,”;
}
}
resultsJson += “]}”;
return resultsJson;
}
Edit: The other way to fix this problem is to use the ([JSON.Net][1]) library. It properly serializes derived classes, and it is well supported.
_*[1]: Newtonsoft

I had a similar problem, I solved it by explicitly using the Serializable attribute on my classes

using System;

[Serializable]
public class GameSettings {
	public float pacManSpeed = 15;
	public float powerPelletTime = 7;
	public GhostSetting inkySetting = new GhostSetting();
	public GhostSetting blinkySetting = new GhostSetting();
	public GhostSetting pinkySetting = new GhostSetting();
	public GhostSetting clydeSetting = new GhostSetting();
}

[Serializable]
public class GhostSetting {
	public float speed = 5;
	public int aggression = 5;
}