-1

I am attempting to write a method that takes in an object and will use the Unity JsonUtility or the JsonHelper and returns the serialized version of that object. When I run the below debugging code everything works correctly.

    object t = new List<Player>
    {
        new Player
        {
            Name = "asdf",
            ID = Guid.NewGuid().ToString()
        }
    };

    if (t is IEnumerable<Player> list)
        Debug.Log(JsonHelper.ToJson(list.ToArray()));

//Result {"Items":[{"ID":"eff6ca08-b464-4e57-9f2e-f49a0cb869ff","Name":"asdf"}]} 

However, my actual method does not return the same thing.

 public void SeriailizeObject<T>(T obj)
 {
    if (obj is IEnumerable<T> list)
    {
        Debug.Log(JsonHelper.ToJson(list.ToArray()));
        //Result {}
    }
    ...

Does anyone know if you can serialize a generic list with Unity's JsonUtility?

Travis Pettry
  • 1,220
  • 1
  • 14
  • 35

1 Answers1

0

When calling SeriailizeObject(new List<Player>()), typeof(T) is equal to List<Player> and obj is not an IEnumerable<List<Player>>.

When calling SeriailizeObject(t), typeof(T) is equal to object and obj is an IEnumerable<object> (assuming that t is a List<Player>).

mm8
  • 163,881
  • 10
  • 57
  • 88