M. Razdrh
M. Razdrh

Reputation: 11

UNITY JSON to Object mapping error

So i have this string that callback function gives which contains all the json data

  private string jsonResponse = @"{""players""[{""name"":""cc"",""rank"":29}, ...]}";

And when i try to convert it from json to object using JsonUtility.FromJson it throws

 Object reference not set to an instance of an object

I've created object classes(root and normal class) and it still doesn't work, here is the code:

void actionTest(int i, string s)
     {
         Debug.Log(i + " " + s);
         Rootobject rootObj = new Rootobject();
         rootObj = JsonUtility.FromJson<Rootobject>(s);
         Debug.Log(rootObj.players.Count);
     }
 [System.Serializable]
 public class Rootobject
 {
     public List<Player> players { get; set; }
 }
 [System.Serializable]
 public class Player
 {
     public string name { get; set; }
     public int rank { get; set; }
 }

This all happens when a button is pressed!

Upvotes: 0

Views: 671

Answers (1)

Rakiah
Rakiah

Reputation: 240

This is a NullReferenceException meaning that one of your fields is NULL, can you actually post at which line exactly you are getting the exception ? if its this one

rootObj = JsonUtility.FromJson<Rootobject>(s);

Then its probably s that is NULL at this time ? also it could be that RootObject have a constructor that is triggering a NullReferenceException, You don't have to construct rootObj since JsonUtility.FromJson will construct the item, if you want to populate your item, you can use JsonUtility.FromJsonOverwrite

Upvotes: 1

Related Questions