- Home /
JsonFX and Polymorphism?
I'm trying to store (readable) data in a text-file as an asset since the class I'm serializing contains many things that Unity itself can't handle.
A problem is though, that even though everything saves and loads, only the base-type is returned. I did a lot of searches on the internet to find a solution and I've tried everything recommended but alas, the problem still resides.
I'm trying to serialize a class with 2 fields, one int and one Dictionary;
Item is the base class with a large variety of children I've had to convert int to string to allow jsonfx to de-serialize the dictionary. The following code is used to serialize and de-serialize the data.
public static string FiletoJSON(object T)
{
try
{
StringBuilder sb = new StringBuilder();
JsonWriterSettings settings = JsonDataWriter.CreateSettings(false);
settings.TypeHintName = "__type";
JsonWriter writer = new JsonWriter(sb, settings);
writer.Write(T);
return sb.ToString();
}
catch(Exception e)
{
Debug.LogWarning(e.InnerException);
return null;
}
}
public static T JSONtoFile<T>(string JSONString)
{
try
{
JsonReaderSettings settings = JsonDataReader.CreateSettings(true);
settings.TypeHintName = "__type";
using (TextReader textReader = new StringReader(JSONString))
{
var jsonReader = new JsonReader(textReader, settings);
return jsonReader.Deserialize<T>();
}
}
catch (Exception e)
{
Debug.LogWarning(e);
return default(T);
}
}
The following is the output of the string.
{
"__type": "ItemDatabase, Assembly-CSharp",
"DatabaseID": 1,
"ItemList":
{
"1":
{
"__type": "Sniper, Assembly-CSharp",
"MaxAmountOfItem": 1,
"RangedAttack": 950,
"WeaponObjectID": 3,
"weaponType": "Sniper",
"Accuracy": 100,
"MaxEnergy": 437,
"SkillSlots": null,
"StatusEffects": null,
"EnergyRestorePerTick": 8,
"EnergyRestoreOverTime": true,
"Variance": 30,
"Cooldown": 1,
"Name": "TestSniper",
"Description": "",
"ID": 1,
"Points": 1,
"Tier": 8
}
}
}
How can I make sure that JsonFX properly de-serializes my sub-types too?
Note: The purpose of this, is storing several dictionaries filled with supertypes. I've managed to accomplish this with a binaryformatter, but there is a noticeable performance reduction compared to using JSON. On top of this, the data in the text file is unreadable.
The only thing that stands out to me is are you passing the base-type as the generic parameter to JSONtoFile()? I use polymorphism with JsonFX and as long as I pass in the sub-type as the generic parameter I get the correct object returned.
I am, and in my case it was the ItemDatabase class. Turns out the dictionary was the main problem as it can handle an array just fine. This is about 8 times slower as binary formatting though.
Answer by Mark Gossage · Jun 08, 2015 at 07:43 AM
Never worked with the JsonReader before, but I have worked with the newtonsoft one & I know that supports polymorphism ok.
I had a base class (Message) with a number of derived classes. I found that I couldn't serilaise a Message polymorphicly, but a Message[] seemed to work just fine.
As for testing: just write a test script:
void Start()
{
Soldier s;
s=new Sniper(){....};
string str=JsonToString(s);
Soldier s2=StringToJson(str);
if (s2 is Sniper)
{
Sniper snip=(Sniper)s2;
Debug.Log(....);
}
else
{
Debug.Log("Polymorthism issue");
}
}
The dictionary was the problem, deserializing that only returns Typeof Item. A list can't even be deserialized it seems.
I've ran a few tests with 10.000 Snipers added. Loading the database from Binary took around 265ms Loading the database from JSON (erroneous) took around 850 ms Loading the database from JSON as Item[] and converting it to a dictionary took ~1850 ms.
Storing the data was almost instnat with binary and took a few seconds with JSON eitherway. The JSON file is also 4 times larger in size.
It's clear that binary is the winner here, but this leaves me with unreadable data.
Your answer
Follow this Question
Related Questions
An OS design issue: File types associated with their appropriate programs 1 Answer
Deserializing Json String 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers