Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Serialized anonymous classes using JsonUtility

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

  1. mahdiii

    mahdiii

    Joined:
    Oct 30, 2014
    Posts:
    856
    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:
    8,513
    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.
  3. Northmaen

    Northmaen

    Joined:
    Jun 23, 2015
    Posts:
    17
    Hey, sorry to necro this post, but there not much resources about this.

    I tried today to serialize an anonymous type, and it returns me an empty json object. It would be nice to be able to serialize this kind of thing.

    One example: creating a new class with partial definition of the same object for patching a database is tedious.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,514
    You probably can, perhaps not with the Unity tiny/lite JSON serializer though.

    Problems with Unity "tiny lite" built-in JSON:

    In general I highly suggest staying away from Unity's JSON "tiny lite" package. It's really not very capable at all and will silently fail on very common data structures, such as Dictionaries and Hashes and ALL properties.

    Instead grab Newtonsoft JSON .NET off the asset store for free, or else install it from the Unity Package Manager (Window -> Package Manager).

    https://assetstore.unity.com/packages/tools/input-management/json-net-for-unity-11347

    Also, always be sure to leverage sites like:

    https://jsonlint.com
    https://json2csharp.com
    https://csharp2json.io
     
  5. Northmaen

    Northmaen

    Joined:
    Jun 23, 2015
    Posts:
    17
    Yeah, I'm well aware of the limitations of Unity's built in Json serializer. But it's built-in, that's big for my use case: creating and hosting custom unity packages on a private registry.
     
  6. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,606
    Pretty sure no work is being done to the JSONUtility class and pretty sure you'll get nowhere using it. Even Unity's own packages just use Newtonsoft.JSON these days.
     
  7. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,912
    Most serializers require the class that is serialized to be marked with the System.Serializable attribute. Anonymous classes do not have this attribute and since the class is constructed implicitly by the compiler you can not tell it to do that.

    While anonymous classes can be quite handy in certain cases, as it was already said, when it comes to serialization it doesn't make too much sense. It may "feel" like you have the freedom you have in dynamic scripting languages, but you don't.

    If you need a simple json parser / generator which should support dynamic results, you can use my SimpleJSON framework. It represents the different json types with explicit classes (so one for string, number, object, array, boolean and null). You can create a json object like that

    Code (CSharp):
    1. JSONNode request = new JSONObject();
    2. request["someField"] = "some string";
    3. request["data"]["someSubField"] = 42;
    4.  
    5. string json = request.ToString(); // packed json
    6. string jsonPretty = request.ToString(3); // indented json
    It is designed in a modular fashion so it can be easily extended. I've also made a Unity extension so you can directly convert some common Unity types (vector types, quaternion, color, ...) to a JSONNode.

    The example above would generate something like
    Code (CSharp):
    1. {
    2.    "someField": "some string",
    3.    "data": {
    4.       "someSubField": 42
    5.    }
    6. }
    With
    JSON.Parse
    you can parse any valid json into the same structure composed of JSONObjects / JSONArrays, ...
     
    Kurt-Dekker likes this.