Convert JSON string to object unity C# - Resolving Null Reference Error

 I have to deal with the JSON response of UnityWebRequest. I tried different methods of the unity builtin JsonUtility class but failed to convert JSON string to C# object as it shows a null reference error when I try to access a property of the converted object of JSON.

First, I converted my JSON string to C# structure classes using this online website and then, added [Serializable] attribute to my class like below code

[Serializable]

public class Root

{

    public int statusCode { get; set; }

    public string message { get; set; }

    public Auth auth { get; set; }

}

When I was trying to convert it using JsonUtility.FromJson, it failed. Although it didn't throw any exception during conversion but failed to convert it as I was unable to log any property of the object.

Root root =    JsonUtility.FromJson<Root>(responseText);
Debug.Log(root .statusCode);


Then, I try another method JsonUtility.FromJsonOverwrite it again failed. 

Root root = new Root();
JsonUtility.FromJsonOverwrite(responseText, root );
Debug.Log(root .statusCode);
       

Then, I use the Newton JSON, and it simply worked.

Root root  = JsonConvert.DeserializeObject<Root>(responseText);
Debug.Log(root .statusCode);

The same class structure perfectly worked with newton JsonConvert.DeserializeObject

I really don't know why it was not working but newton json save my time. I recommend you to use it instead builtin JsonUtility class.
      

Post a Comment

0 Comments