lundi 22 mai 2017

Dynamically serialize List to JSON using reflection in Unity

I'm having a quite complex situation in which I would like some advice to solve this situation. So I asked this question earlier: Unity save everything (snapshot)

And I'm currently trying to serialize everything into JSON. Whilst serializing everything I have a few requirements.

  1. I do not know which components are attached to a gameobject.
  2. I do not know what these components (classes) have for properties/fields.

I succeeded in serializing the basic types of unity (transform/meshrenderer etc). However I'm now working on code to serialize custom components. For this I use reflection. This code works if a class only has primary types (string,int,float, etc). However I still face two challenges.

  1. Serializing a list without knowing it's type (or at least knowing the type but unable to dynamically cast it with my knowledge)
  2. Serializing fields that contain custom classes (and lists which contains custom classes).

For now I would like to get advice primarily on point one. I developed this code: Type is as string that I got earlier

if (type.Contains("List"))
{
    value = serializeListVariable(singular.GetValue(comp));
}

Then here is the method which should serialize the list. With debugging I can see the objects are in the values variable. However they are not convertednvert them to JSON and just returns {}. In this first iteration I would like to dynamically save lists of primary types. But later I would like to do this with custom classes as well. If I do tostring with getvalues I'm able to get a correct JSON string afterwards, But then again I don't have influence on the tostring method of these custom classes...

private string serializeListVariable(object listobject)
{
    PropertyInfo listitems = listobject.GetType().GetProperty("Item");
    int listcount = (int)listobject.GetType().GetProperty("Count").GetValue(listobject, null);
    var values =  new object[listcount];
    for (int i =0; i < listcount; i++) {

        values[i] = listitems.GetValue(listobject, new object[] { i });
    }
    string serializedlist = JsonHelper.ToJson(values);
    return serializedlist;
}

The JSON helper method that is called:

public static string ToJson<T>(T[] array)
{
    Wrapper<T> wrapper = new Wrapper<T>();
    wrapper.Items = array;
    return JsonUtility.ToJson(wrapper);
}

And the wrapper class that is mentioned:

[Serializable]
private class Wrapper<T>
{
    public T[] Items;
}

Hopefully some of you know to solve this problem.

Thanks in advance!





Aucun commentaire:

Enregistrer un commentaire