Hey,
We have written a standalone editor application for of our products, in which users can create questions with matching answers (correct of incorrect). When users are editing this data, we save the progress to a text file in JSON format, so user can continue where they left off.
So the basic setup for a question is this:
public record TextQuestionData : QuestionData
{
[SerializeField] private string question = string.Empty;
[SerializeField] private string info = string.Empty;
[SerializeField] private List<StringAnswerData> correctAnswers = new List<StringAnswerData>();
[SerializeField] private List<StringAnswerData> incorrectAnswers = new List<StringAnswerData>();
}
And the StringAnswerData looks like this:
public record StringAnswerData : AnswerData
{
[SerializeField] private string answer = string.Empty;
}
In both cases, the data it inherits from has some additional data (AnswerData has nothing yet) which in turn inherit from BaseData, that allows us to monitor property changes.
In case it matters:
[Serializable]
public record BaseData : IBindableDataType, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected BaseData() { }
protected void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
protected bool SetField<T>(ref T field, T value, bool skipCompare = false, [CallerMemberName] string propertyName = "")
{
if (!skipCompare && EqualityComparer<T>.Default.Equals(field, value))
{
return false;
}
field = value;
OnPropertyChanged(propertyName);
return true;
}
}
Now, for the issue: We noticed in some cases, that when some of the answers were adjusted, some of the other values changed with it. After some digging around in code, checking missed sub/unsubs, I found the issue was likely with how the data was serialized and deserialized.
For example, this is how one of the questions (in JSON) looks:
"correctAnswers": {
"_list": [
{
"$id": 2,
"answer": "1"
},
{
"$id": 3,
"answer": "1"
}
]
},
"incorrectAnswers": {
"_list": [
{
"$ref": 2
},
{
"$ref": 3
}
]
},
So for some reason (without my know how) sometimes the answers are changed to a reference to another answer.
We are using the Serialization Unity Package (v 3.1.2) to write and read to and from.
Writing is simply:
string jsonData = JsonSerialization.ToJson(SelectedProject);
Reading is simply:
projectData = JsonSerialization.FromJson<ProjectData>(data);
Also probably worth noting that it does’t happen all the time. I have not been able to figure out yet how this is happening.
If anyone is able to shed some light on how this can happen, and more importantly, how I can prevent it. that would be great.