skip to Main Content

I’m doing a little exercise to get values from a JSON file and set those values into InputFields of a Unity project.

When I read the file all I can get is that the Index is out of range, when counting the elements inside the List it returns 0 elements.

lista.json:

{
  "personajes":[
      {"nombre":"Pepe","apellido":"Lereie","puntos":15},
      {"nombre":"David","apellido":"Garcia","puntos":99}
  ]
}

Usuarios class

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Usuarios
{
    public string nombre;
    public string apellido;
    public int puntos;

}
Personajes class

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class Personajes 
{
   public List<Usuarios> personajes = new List<Usuarios>();

}

Controller Script from Unity

using System.Collections;
using System.Collections.Generic;
using System.IO;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class MenuController : MonoBehaviour
{
    public TMP_InputField entradaNombre, entradaApellidos, entradaPuntos;
    string fichero;
    string datos;
    Personajes lista;

    void Awake()
    {

        fichero = Application.dataPath + "/Files/lista.json";
        datos = File.ReadAllText(fichero);
        lista = JsonUtility.FromJson<Personajes>(datos);

        Debug.log(lista[0].nombre);
    }

}

In this case the console output should be "Pepe" but the only thing I get is Index out of range.

Update:

Also tried the solution from Serge and getting the same output.

 Debug.log(lista.personajes[0].nombre);

2

Answers


  1. after deserialization, you have an object, not a list. So try this

    lista = JsonUtility.FromJson<Personajes>(datos);
    
     Debug.log(lista.personajes[0].nombre);
    

    IMHO , this would be more clear

     List<Usuarios> personages = JsonUtility.FromJson<Personajes>(datos).personages;
    
    Debug.log(personajes[0].nombre);
    

    and remove list init from the class

    public class Personajes 
    {
       public List<Usuarios> personajes;
    
    }
    

    if you still have some problem or not, I highly recommend you to install Newtonsoft.Json for Unity3d ( you can google to find it), and use this code

    List<Usuarios> personajes = JsonConvert.DeserializeObject<Personajes>(json).personajes;
    
    Debug.log(personajes[0].nombre);
    
    Login or Signup to reply.
  2. So close, but it looks like you forgot to decorate Usuarios with [System.Serializable] as well:

    [System.Serializable]
    public class Usuarios
    {
        public string nombre;
        public string apellido;
        public int puntos;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search