How to write and read Json in Unity

i have a problem with unity and Json. Well i need to save a name and score from a game, i think Json it’s a great option but i never used them.

I understand the basics, how to read one JsonObject but the problem i don’t know how to creat a new object.

later i try to create an array of object in Json and i dont know hoy read them.

this is my idea.

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


public class Score : MonoBehaviour {
    string path;
    string jsonString;
    // Use this for initialization
    void Start () {
        path = Application.dataPath + "/ScoreRecords.json";
        jsonString = File.ReadAllText (path); 
        ListaRecords listaRecords = JsonUtility.FromJson<ListaRecords> (jsonString);
        print(listaRecords);
        foreach(Record record in listaRecords){
            Debug.Log ("nombre: " + record.name + "score: " + record.score);
        }

    }

    // Update is called once per frame
    void Update () {

    }
}


[System.Serializable]
public class Record{
    public string name;
    public int score;
}

[System.Serializable]

public class ListaRecords{
    public List<Record> Records;
}

and this is my Json

{
    "Records": [
        {"nombre":"daniel", "puntos":100},
        {"nombre":"Adrian", "puntos":200}
    ]
}

Unity’s JsonUtility is an object mapper. That means the names of the fields have to match the keys in your json data. So if you you want to go with your JSON data you should change your Record class to:

[System.Serializable]
public class Record{
    public string nombre;
    public int puntos;
}

If you want to keep the code you have to change your JSON to

{
    "Records": [
        {"name":"daniel", "score":100},
        {"name":"Adrian", "score":200}
    ]
}

If you want more flexibility you may want to use a more generic JSON framework like my SimpleJSON. With it you can directly parse and access the JSON data like this:

jsonString = File.ReadAllText (path); 
JSONNode data = JSON.Parse(jsonString);
foreach(JSONNode record in data["Records"])
{
    Debug.Log ("nombre: " + record["nombre"].Value + "score: " + record["puntos"].AsInt);
}