deniszykov / msgpack-unity3d

MessagePack and JSON serializer for Unity3D

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Can we deserialize directly to already created object?

mabakay opened this issue · comments

Hi, in Unity you can image simple case when deserialized is class which inherits from MonoBehaviour. Then I have to create it by using AddComponent method to be able to attach it.

Hi, there is no such feature. But you can deserialize in a dictionary and then assign fields through reflection.

It's just an example code, it's naive, but it shows the idea:

var instance = new MyType();
var instanceType = instance.GetType();
var fields = (IndexedDictionary<string, object>)Json.Deserialize(typeof(object), json);

foreach(var kv in fields)
{
    var fieldName = kv.Key;
    var fieldValue = kv.Value;
    var property = instanceType.GetProperty(fieldName/* ... bindingflags etc. */);
    if (property  == null) continue;

    var value = Convert.ChangeType(fieldValue, property.PropertyType); // naive
    property.SetValue(instance , fieldValue);
}