Loop through Json and add result in array?

Hi,
I would like to load multiple lines like character statistics, they all have “name” and “power” for example. I don’t know how to loop through the result in comment. So I tried with this link, it talks about a List, but here the .Count of the list gives 0. Would you know how to solve one or the other way? Thanks

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

[System.Serializable]
public class PlayerStats{

    public int life;
    public string name;
    public int energy;
}

[System.Serializable]
public class PlayerStatsList {

    public List <PlayerStats> playerStats;
}

public class Sauvegarde : MonoBehaviour
{
 
    public PlayerStatsList myPlayerStatsList = new PlayerStatsList();

    void Start () {
        string jsonText = File.ReadAllText(Application.dataPath + "/Scripts/characters.json");
        JsonUtility.FromJsonOverwrite(jsonText, myPlayerStatsList);
        Debug.Log("jsonText : "+jsonText);//works
        Debug.Log("count : "+myPlayerStatsList.playerStats.Count);// = 0
        foreach (PlayerStats p in myPlayerStatsList.playerStats){
            Debug.Log("life : "+p.life);
        }
        //Person[] p = CreateFromJSON(mj); //error : Cannot convert Person to Person[]....
    }
    /*
    public Person[] CreateFromJSON(string jsonString){
        return JsonUtility.FromJson<Person[]>(jsonString);
    }
    */
}

The json is like that :

{
    "PlayerStats": [
        {
            "life": "10",
            "name": "Kratos",
            "energy": 100
        },
        {
            "life": "80",
            "name": "Nathan",
            "energy": 20
        },
        {
            "life": "90",
            "name": "Link",
            "energy": 25
        }
    ]
}

Can you try using FromJson instead and see if that works?

1 Like

Did you build the json by hand?

The json doesn’t seem like it would match your classes. “PlayerStats” should for one be “playerStats”, as it’s supposed to match the variable name, not the class name.

3 Likes

Also, “life” in your json is a string (surrounded by quotes), but is an int in your code.

3 Likes

Guys thank you very much. It was indeed mistakes in the code.

Can you post the fixed code?

Many thanks

Sorry I did not keep the code, I erased the project at the time.