Saving/Loading class list with SimpleJSON,Saving class list with SimpleJSON

Hi, I don’t know what’s wrong. On save it saves it but on load it loads it only in string.

class list:

public class BuildingData

{
    public int placeID;
    public float upgradePrice;
    public int upgradeLevel;
    public int happinessValue;
    public float peoplePerSec;
    public string buildingName;
    public int buildingPrice;
    public int buildingLevel;
    public float buildingProduction;
    public int buildingID;
}

code:

void Start(){
    Load<BuildingData>("key1");
}

public void AutoSave(){
    Save<BuildingData>("key1", buildingData);
}

public static void Save<BuildingData>(string key, List<BuildingData> objs){
    JSONArray jsonArray = new JSONArray();
    foreach(BuildingData obj in objs){
        try{
            string jsonObjString = JsonUtility.ToJson(obj);
            jsonArray.Add(JSON.Parse(jsonObjString));
            Debug.Log(objs);
        }
        catch(Exception e){

        }
    }
    PlayerPrefs.SetString(key, jsonArray.ToString());
    Debug.Log("Saved" + jsonArray.ToString());
}

public static List<BuildingData> Load<BuildingData>(string key){
    List<BuildingData> objs = new List<BuildingData>();

    string jsonString = PlayerPrefs.GetString(key, "[]");
    Debug.Log("LOAD String " + jsonString);
    try{
        JSONArray jsonArr = (JSONArray)JSON.Parse(jsonString);
        Debug.Log("LOAD Array " + jsonArr);
        foreach(JSONObject jsonObj in jsonArr){
            objs.Add(JsonUtility.FromJson<BuildingData>(jsonObj.ToString()));
            Debug.Log("LOAD Object " + jsonObj);
        }
    }
    catch(Exception e){

    }
    return objs;
}

}

Well your usage of my SimpleJSON library is quite strange since you still use Unity’s JsonUtility and convert your date several times to / from json. Of course this should work, though it not that efficient ^^.

Anyways your Load method return the loaded “BuildingData” list. However you call your Load method inside Start but you essentially do nothing with the returned List. So I guess that’s your issue?

You probably want to do something like this:

void Start() {
    buildingData = Load<BuildingData>("key1");
}

instead of

void Start() {
    Load<BuildingData>("key1");
}

edit

Since you still use Unity’s JsonUtility, wouldn’t it be simpler to just create a root class that contains the List you want to save?

[System.Serializable]
public class SaveDataRoot
{
    public List<BuildingData> buildings = new List<BuildingData>();
}

Unity’s JsonUtility can serialize this class just fine. Just keep in mind that the top most node has to be an object and not an array. The only reason for your workaround would be that you really need an array as top most element for other reasons.

Another option would be to use the Json.NET library instead.