Hi,
I am serializing and deserializing items in my scene to save/load the items.
I have successfully serialized properties into a PropertyData object:
[System.Serializable]
public class PropertyData
{
public string Name;
public string Type;
public object Value;
}
Here’s the serialization code:
public List<PropertyData> SerializeProperties()
{
var list = new List<PropertyData>();
var type = this.GetType();
var properties = type.GetProperties(/*blablabla*/);
for(int i = 0; i < properties.Length; i++)
{
var property = properties[i];
var data = new PropertyData();
data.Name = property.Name;
data.Type = property.PropertyType.FullName;
data.Value = property.GetValue(this);
list.Add(data);
}
return list;
}
The list of PropertyData objects is then stored in another object that gets converted using Newtonsoft.JSON.
Here’s for example the result for a bool and a color property.
"Items": [
{
"Name": "My Serialized Item 1",
"Id": "342354",
...
"Properties": [
{
"Name": "Visible",
"Type": "System.Boolean",
"Value": false
},
{
"Name": "Color",
"Type": "UnityEngine.Color",
"Value": {
"r": 1.0,
"g": 0.0,
"b": 0.0,
"a": 1.0,
"grayscale": 0.299,
"maxColorComponent": 1.0
}
}
]
},
...
]
}
But now I can’t reverse the process properly. Here’s the deserialization code:
protected void DeserializePropertyData(PropertyData data)
{
var p = this.GetType().GetProperty(data.Name);
if(p == null)
{
return;
}
var type = p.PropertyType;
// SOMETHING NEEDS TO BE DONE TO CONVERT data.Value to the correct object
p.SetValue(this, data.Value);
}
This results in: ArgumentException: Object of type 'Newtonsoft.Json.Linq.JObject' cannot be converted to type 'UnityEngine.Color'
I’m kinda blank right now. Does anyone have an idea? Perhaps the whole approach is wrong?