Search Unity

  1. Unity 2019.1 is now released.
    Dismiss Notice

Serialized anonymous classes using JsonUtility

Discussion in 'Scripting' started by mahdiii, Mar 15, 2019.

  1. mahdiii

    mahdiii

    Joined:
    Oct 30, 2014
    Posts:
    799
    Hi. Can we serialize anonymous classes using JsonUtility?

    Code (CSharp):
    1. var request=new {Content=new Request(...)}
    2. var json=JsonUtility.ToJson(request);
    3.  
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    6,437
    I haven't tested (you could give it a simple try).

    I bet it will serialize because anonymous types do technically have types, they're just weird gibberish names stored in the background and you don't necessarily easily know them.

    BUT

    Deserializing, that'll be a problem. Since JsonUtility expects you to tell it what type to deserialize to, and since you don't know the type, well... there's no way to tell it.

    (well I could come up with a hack way to get the anonymous type's type and reflect out the FromJson static method and create the generic version for that refleted anon type... but that's getting really hacky at that point).
     
    mahdiii likes this.