So i modified a json serialization script documented here: https://unitygem.wordpress.com/json-serializer/ because i needed to write a system that could save arrays of multiple different classes that inherit from a parent class.
Since the script for some reason doesn’t have support for serializing arrays that aren’t classes, I easily added that feature myself, improving the script a bit everywhere along the way.
but now when trying to deserialize my json, i get error mentioned in the title:
//o is my object. info is a feildinfo representing the field i want to set. rootObject is an object created with Activator.CreateInstance(rootType) that will be outputted by the deserializer
info.SetValue(rootObject, o);
A little bit of research later i had a chain of if statements that fixed the problem using linq casts:
if(attrFieldType == typeof(string)){
info.SetValue(rootObject, o.Cast<string>().ToArray());
}else if(attrFieldType == typeof(float)){
info.SetValue(rootObject, o.Cast<float>().ToArray());
}else if(attrFieldType == typeof(int)){
info.SetValue(rootObject, o.Cast<int>().ToArray());
}else if(attrFieldType.IsEnum){
o = o.Cast<string>().Select(x => Enum.Parse(attrFieldType, x.ToString()));//convert from string first
if(attrFieldType == typeof(imAnEnum)){
info.SetValue(rootObject, o.Cast<imAnEnum>().ToArray());
}else if(/*test for another enum!*/){
}else if(/*and another!*/){
}else if( ect...
}
Now this would be ok, if i didn’t have to store many data types, but i do. After a full day of trying to figure out how to make this work, Ive run out of ideas.
I can’t do things like o.cast or o.cast(type-variable).
So what other way is there of doing this? and why can’t the SetValue convert the object to the correct datatype itself in the first place?
Also trying things like this work fine for classes but not for ints, floats, enums, or anything else, and i can’t figure out why:
object o = Array.CreateInstance(type, jsonArray.Length);
object[] objs = (object[])o;//error: InvalidCastException: Cannot cast from source type to destination type.
//add stuff to objs. works very well for setting arrays of classes
info.SetValue(rootObject, o);
Thanks in advance for any help