Search Unity

Decoding JSON to an Object

Discussion in 'Scripting' started by lior_rosenspitz, Apr 22, 2015.

  1. lior_rosenspitz

    lior_rosenspitz

    Joined:
    Jan 24, 2015
    Posts:
    24
    Hi,
    I would be happy for tips how to manage and deserialize a mixed JSON file (which has string, other JSONs, arrays and more).

    I'm trying to decode the following JSON file, using 'JSONobject' plugin.
    https://api.myjson.com/bins/zazd

    It was loaded just fine (i'm loading the whole text to text-object).
    I also had created a class and inner classes that will match the JSON structure, and I managed the code to create on runtime the amount of main objects the json has (for example, it has a list of 3 types of donuts, so the code create an array of 3 'donuts' objects, and I can see it from the inspector).
    Also I could easily printed to the log all keys and value, which are mixed types.

    The problem began when i'm trying to load the inner data (as ID or name of one of those inner JSON objects) into the class that had been created.
    I get the error: "NullReferenceException: Object reference not set to an instance of an object".
    Any ideas?


    /////////////////////////////////////////////////////////
    /// Decoder - Working progress... ///
    ///////////////////////////////////////////////////////
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using UnityEngine.UI;
    4.  
    5. public class Json_Decoder_Work: MonoBehaviour {
    6.  
    7.     public string url_json = "https://api.myjson.com/bins/zazd";
    8.     public GameObject TextViewer;
    9.  
    10.     // Internal variables
    11.     private bool isInternalBatters;
    12.     private bool isInternalTopping;
    13.     private bool isExternal;
    14.     private bool isID;
    15.     private bool isType;
    16.     private bool isName;
    17.     private bool isPPU;
    18.  
    19.     // Temporary variables
    20.     private int tempObjectIndex;
    21.     private DounutObject tempObject;
    22.     private int tempID;
    23.     private string tempType;
    24.     private string tempName;
    25.     private float tempPPU;
    26.  
    27.     // Load & Present the JSON String text
    28.     IEnumerator Start() {
    29.  
    30.         // Get the JSON text from web
    31.         WWW wwwOBJ = new WWW(url_json);
    32.         yield return wwwOBJ;
    33.  
    34.         // Load the JSON text into string
    35.         TextViewer.GetComponent<Text>().text = wwwOBJ.text;
    36.  
    37.         // DeSerialize the json string into object
    38.         JSONObject j = new JSONObject(wwwOBJ.text);
    39.         accessData(j);                                  
    40.     }
    41.  
    42.  
    43.     //access data (and print it) - CHANGED
    44.     void accessData(JSONObject obj)
    45.     {
    46.         switch(obj.type)
    47.         {
    48.         case JSONObject.Type.OBJECT:
    49.             for(int i = 0; i < obj.list.Count; i++)
    50.             {
    51.                 string key = (string)obj.keys[i];
    52.  
    53.                 switch (key) {
    54.                 case "data":
    55.                     isExternal = true;
    56.                     break;
    57.                 case "batter":
    58.                     isInternalBatters = true;
    59.                     break;
    60.                 case "topping":
    61.                     isInternalTopping = true;
    62.                     break;
    63.                 case "id":
    64.                     Debug.Log("updating ID :) :) :)");
    65.                     if (!isInternalBatters && !isInternalTopping)
    66.                     {
    67.                         isID = true;
    68.                         Debug.Log("ID -> ON!");
    69.                     }
    70.                     break;
    71.  
    72.                 default:
    73.                     break;
    74.                 }
    75.  
    76.                 JSONObject j = (JSONObject)obj.list[i];
    77.                 Debug.Log(" I=" + i + "->");
    78.                 Debug.Log(key);
    79.                 accessData(j);
    80.                 Debug.Log("<-");
    81.             }
    82.             break;
    83.  
    84.         case JSONObject.Type.ARRAY:
    85.             if (isExternal){
    86.                 ObjectsManager.controller.food = new DounutObject[obj.list.Count];
    87.                 Debug.Log("JSON contains object x" + obj.list.Count);
    88.                 isExternal = false;
    89.  
    90.                 tempObjectIndex = 0;
    91.  
    92.                 for (int i = 0 ; i<obj.list.Count; i++)
    93.                 {
    94.                     JSONObject j = obj.list[i];
    95.                     accessData(j);
    96.                     tempObjectIndex++;
    97.                 }
    98.             }
    99.             if (isInternalTopping){
    100. //                toppings[] tempTop = new toppings[obj.list.Count];
    101. //                ObjectsManager.controller.food[0].setTopping(obj.list.Count);
    102.                 Debug.Log("Topping has" + obj.list.Count + " layers");
    103.                 isInternalBatters = false;
    104.             }
    105.             if (isInternalBatters){
    106. //                ObjectsManager.controller.food[tempObjectIndex].setBatter(obj.list.Count);
    107.                 Debug.Log("Batters has" + obj.list.Count + " layers");
    108.                 isInternalBatters = false;
    109.             }
    110.  
    111.             break;
    112.  
    113.  
    114.  
    115.         case JSONObject.Type.STRING:
    116.             Debug.Log(obj.str);
    117.             if (isID && !isInternalBatters && !isInternalTopping){
    118.                 ObjectsManager.controller.food[tempObjectIndex].id = obj.str;
    119.                 isID = false;
    120.                 Debug.Log("ID -> OFF");
    121.             }
    122.             break;
    123.  
    124.         case JSONObject.Type.NUMBER:
    125.             Debug.Log(obj.n);
    126.             break;
    127.  
    128.         case JSONObject.Type.BOOL:
    129.             Debug.Log(obj.b);
    130.             break;
    131.  
    132.         case JSONObject.Type.NULL:
    133.             Debug.Log("NULL");
    134.             break;  
    135.         }
    136.     }
    137. }

    // Object Manager
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class ObjectsManager : MonoBehaviour {
    5.  
    6.     public static ObjectsManager controller;
    7.     public DounutObject[] food;
    8.  
    9.     void Awake(){
    10.         controller = this;
    11.     }
    12.  
    13.     public void updateID (int position , string id) {
    14.         food[position].setID(id);
    15.     }
    16.  }
    // Object class
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. [System.Serializable]
    5. public class DounutObject {
    6.     public string id;
    7.     public string type;
    8.     public string name;
    9.     public float ppu;
    10.     public batters[] batter;
    11.     public toppings[] topping;
    12.  
    13.  
    14.     // Set topping
    15.     public void setTopping (int amount) {
    16.         this.topping = new toppings[amount];
    17.     }
    18.  
    19.     // Set Batter
    20.     public void setBatter (int amount) {
    21.         this.batter = new batters[amount];
    22.     }
    23.  
    24.     public void setID (string idX)
    25.     {
    26.         this.id = idX;
    27.     }
    28. }
    29.  
    30. [System.Serializable]
    31. public class batters {
    32.     public int id;
    33.     public string type;
    34. };
    35.  
    36. [System.Serializable]
    37. public class toppings {
    38.     public int id;
    39.     public string type;
    40. }
    41.  
     
  2. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    What line of code is actually throwing the exception?