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

JsonUtility can't deserialize nullable variables

Discussion in 'Scripting' started by HedgehogNSK, Feb 24, 2020.

  1. HedgehogNSK

    HedgehogNSK

    Joined:
    Jun 3, 2017
    Posts:
    24
    Hello. I can't find out how to solve problem that JsonUtility.Deserialize method changes null values to default values from json.

    Code (CSharp):
    1.   static public class JsonHelper
    2.     {
    3.         [Serializable]
    4.         private class Wrapper<T>
    5.         {
    6.             public T[] array = null;          
    7.         }
    8.         public static T[] AsArray<T>(this string json)
    9.         {
    10.             try
    11.             {
    12.                 string newJson = "{ \"array\": [" + json + "]}";
    13.                 Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(newJson);
    14.                 return wrapper.array;
    15.             }
    16.             catch(Exception ex)
    17.             {
    18.                 Debug.LogError(ex.Message);
    19.                 throw ex;
    20.             }
    21.         }    
    22.   }
    So I found another Json deserializer in library Pathfinding.Serialization.JsonFx. But Unity doesn't build the project with this library and throws an error:

    Assets\_Project\Scripts\Utility\JsonHelper.cs(7,7): error CS0246: The type or namespace name 'Pathfinding' could not be found (are you missing a using directive or an assembly reference?)


    What options do I have?
     
  2. tonemcbride

    tonemcbride

    Joined:
    Sep 7, 2010
    Posts:
    1,083
  3. HedgehogNSK

    HedgehogNSK

    Joined:
    Jun 3, 2017
    Posts:
    24
    Thanks for reply. But that's not what I need.
    I need deserialize json which I get from derived server where some values are nulls. For example, it can be some path to icon of some item in the game and item can have no icon; or it can be some integer field which in some circumstances must be null (if integer represents character on battlefield, and character is outside).
     
  4. tonemcbride

    tonemcbride

    Joined:
    Sep 7, 2010
    Posts:
    1,083
    HedgehogNSK likes this.
  5. HedgehogNSK

    HedgehogNSK

    Joined:
    Jun 3, 2017
    Posts:
    24
    tonemcbride likes this.