The REST service I am using, RSA Archer, is expecting an integer key which means I simply can't nest [Serializable]
objects and then JsonUtility.ToJson()
to create the serialized JSON string. I thought I found a solution to create a Dictionary
object and then use ISerializationCallbackReceiver
to handle just the dictionary piece of the nested structure, but the code below simply ignores that part of the nested object and doesn't serialize the Dictionary
. Does anyone have any thoughts on the best approach to this?
Expected Output:
{"Content": {"LevelId": 10,"FieldContents": {"47": {"Type": 1, "Value": "me", "FieldId": 47}}}}
Object Structure:
[Serializable]
public class Record
{
public Content Content;
}
[Serializable]
public class Content
{
public int LevelId;
public FieldContents FieldContents;
}
public class FieldContents : ISerializationCallbackReceiver
{
public Dictionary<string, FieldValue> FieldValues;
public List<string> dicKeys;
public List<FieldValue> dicVals;
public void OnBeforeSerialize ()
{
dicKeys.Clear ();
dicVals.Clear ();
foreach (var kvp in FieldValues) {
dicKeys.Add (kvp.Key);
dicVals.Add (kvp.Value);
}
}
public void OnAfterDeserialize ()
{
FieldValues = new Dictionary<string, FieldValue> ();
for (int i = 0; i < Math.Min (dicKeys.Count, dicVals.Count); i++) {
FieldValues.Add (dicKeys [i], dicVals [i]);
}
}
}
[Serializable]
public class FieldValue
{
public int Type;
public string Value;
public int FieldId;
}
JSONUtility and Instantiation:
Record newRecord = new Record () { Content = new Content () {
LevelId = 10,
FieldContents = new FieldContents () { FieldValues = new Dictionary<string, FieldValue> () { {
"47",
new FieldValue () {
Type = 1,
Value = "me",
FieldId = 47
}
}
}
}
}
};
Debug.Log (JsonUtility.ToJson (newRecord));