Search Unity

Resolved problem with JsonHelper

Discussion in 'Scripting' started by Chinard, Jan 1, 2022.

  1. Chinard

    Chinard

    Joined:
    Mar 31, 2018
    Posts:
    11
    Hello and happy new years to all:)

    I try to get the information of json but i have a problem, the array "listNiveauArray" is null.
    the string "contentJsonListNiveau" is correctly completed, I verified with debug.log.

    I alredy used correctly JsonHelper with another script.

    Thanks to your answer.

    Code (CSharp):
    1.  
    2.         contentJsonListNiveau = File.ReadAllText(getScriptDisplayActivity.pathJson + cutName[0] +".json");
    3.         ListNiveauClass[] listNiveauArray = JsonHelper.FromJson<ListNiveauClass>(contentJsonListNiveau);
    4.         Debug.Log(listNiveauArray);

    Code (CSharp):
    1.     public class ListNiveauClass
    2.     {
    3.         public int Niveau;
    4.         public string Goal;
    5.         public int Succes;
    6.     }
    7.  
    8.     public static class JsonHelper
    9.     {
    10.         public static T[] FromJson<T>(string json)
    11.         {
    12.             Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(json);
    13.             return wrapper.Item;
    14.         }
    15.  
    16.         public static string ToJson<T>(T[] array)
    17.         {
    18.             Wrapper<T> wrapper = new Wrapper<T>();
    19.             wrapper.Item = array;
    20.             return JsonUtility.ToJson(wrapper);
    21.         }
    22.  
    23.         public static string ToJson<T>(T[] array, bool prettyPrint)
    24.         {
    25.             Wrapper<T> wrapper = new Wrapper<T>();
    26.             wrapper.Item = array;
    27.             return JsonUtility.ToJson(wrapper, prettyPrint);
    28.         }
    29.  
    30.         [Serializable]
    31.         private class Wrapper<T>
    32.         {
    33.             public T[] Item;
    34.         }
    35.     }

    And the json

    Code (JavaScript):
    1. {
    2.      "Item": [
    3.         {
    4.             "Niveau" : 1,
    5.             "Goal" : "Ffffffffffffff",
    6.             "Succes" : 0
    7.         },      
    8.         {
    9.             "Niveau" : 2,
    10.             "Goal" : "Ffffffffff",
    11.             "Succes" : 0
    12.         }
    13.     ]
    14. }
     
  2. Chinard

    Chinard

    Joined:
    Mar 31, 2018
    Posts:
    11
    Résolved I forget Serializable :(


    Code (CSharp):
    1.  [COLOR=#ff0000][Serializable][/COLOR]
    2.   public class ListNiveauClass
    3.     {
    4.         public int Niveau;
    5.         public string Goal;
    6.         public int Succes;
    7.     }