Hi, I’ve been fighting a lot with serialization lately. I have finally settled on using Newtonsoft Json to do my serialization. I’m using the following functions to save and load a class I call Profile:
public static void Save(Profile profile)
{
if (profile == null) {
return;
}
if (!Directory.Exists(SAVE_PATH)) {
Directory.CreateDirectory(SAVE_PATH);
}
string jsonString = JsonConvert.SerializeObject(profile);
File.WriteAllText(GetProfileFilePath(profile.Name), jsonString);
}
public static Profile Load(string profileName)
{
if (File.Exists(GetProfileFilePath(profileName))) {
string jsonString = File.ReadAllText(GetProfileFilePath(profileName));
Profile profile = JsonConvert.DeserializeObject<Profile>(jsonString);
return profile;
}
return new Profile(profileName);
}
However, I ran into an issue where my profile class is serialized correctly into a Json file when I save. However, my load function is not returning the correct profile. It just generates a new instance of Profile with all default values.
Is there a way to figure out what the deserialization is having issues with?
public class Profile
{
public const string DEFAULT_PROFILE_NAME = "Default";
public const string LAST_PROFILE_KEY = "last-profile";
public string Name { get; private set; }
public CoopManager Coops { get; private set; }
public Player Player { get; private set; }
public GameDay CurrentDay { get; private set; }
public MarketData Market { get; private set; }
public Profile(string name)
{
Name = name;
Coops = new CoopManager();
Coops.Setup();
Player = new Player();
CurrentDay = new GameDay();
Market = new MarketData();
InitializeRacingHistory();
}
private void InitializeRacingHistory()
{
InitializedRaceSimulator simulator = new InitializedRaceSimulator(Coops.RacingCoop);
int totalRacesForEachRaceType = 10;
simulator.Simulate(totalRacesForEachRaceType);
Coops.EvaluateRankings();
}
public void IncrementDay()
{
CurrentDay.Increment();
Coops.IncrementDay(CurrentDay.Day);
Market.Willows.IncrementDay();
}
}
You tell it to create a new profile if it can’t find one. Does the load function actually find the file?
Private setters might be a problem, as the serializer probably can’t set those fields.
Apparently you can use [JsonProperty] attribute on those fields to keep the setters private
Serializers tend to prefer or even require default parameterless constructors when they are recreating an object.
You could try adding one of those as well.
Yes, I am finding the file. I determined that it does run line 19.
Your JsonProperty did the trick. Thanks!
I guess its because when it deserializes that it doesn’t have access to those variables. I wish you could get some details about which variables are failing to deserialize.