Search Unity

JsonUtility.FromJson to a dynamic object?

Discussion in 'Scripting' started by IntDev, Dec 23, 2015.

  1. IntDev

    IntDev

    Joined:
    Jan 14, 2013
    Posts:
    152
    I don't want to tie the json to a type. Is it possible to make it a dynamic object?

    Something like:
    Code (CSharp):
    1. var json = JsonUtility.FromJson<dynamic>(asset.text);
    This actually fires no error, but I don't know how to access the fields.
     
  2. superpig

    superpig

    Drink more water! Unity Technologies

    Joined:
    Jan 16, 2011
    Posts:
    4,659
    Hi,

    No, this is not possible because we need to know the field names and types in order to deserialise the JSON data.

    If you want totally 'unstructured' JSON access (i.e. Dictionary<string, object> style) then you'll need to use a different JSON library for now.

    If you know that the JSON data conforms to one of a set of types but you won't know exactly which one until you deserialise it and check some values, then you can deserialize it multiple times, like this:

    Code (csharp):
    1.  
    2. [Serializable] public struct CommonFields
    3. {
    4.   public string typeName;
    5. }
    6.  
    7. var cf = JsonUtility.FromJson<CommonFields>(json); // fields other than 'typeName' will just be ignored
    8.  
    9. switch(cf.typeName)
    10. {
    11.   case "type1":
    12.     return JsonUtility.FromJson<TypeOne>(json);
    13.   case "type2":
    14.    return JsonUtility.FromJson<TypeTwo>(json);
    15.   // etc...
    16. }
    17.  
     
    Reticulum and IntDev like this.