1

I am trying to read the variables of a json array that is read in a Unity script. This is what I have:

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

public class json_example02 : MonoBehaviour
{

    public string[] newObject;
    
    void Start()
    {

        Debug.Log("jsonScript start");

        // create object
        jasonClass newObject = new jasonClass();

        // read from json file: succesful
        string jsonread = File.ReadAllText(Application.dataPath + "/valuesexample.json");  
        newObject = JsonUtility.FromJson<jasonClass>(jsonread);

        Debug.Log(newObject.Values.Length);// reads correctly

        // trying to acces variables here, but it returns empty
        Debug.Log("Values: " + newObject.Values[0]);
        Debug.Log("Values: " + newObject.Values[1]);
        Debug.Log("Values: " + newObject.Values[2]);

        // write to file: succesful
        string jsonwrite = JsonUtility.ToJson(newObject);
        File.WriteAllText(Application.dataPath + "/saveFileReturn.json", jsonwrite);
       
    }


    [Serializable]
    public class jasonClass
    {
        public Valuesarray[] Values;
    }

    [Serializable]
    public class Valuesarray
    {
        public string Text;
        //public string Text2;
    }
}

This is the format of the json read file:

{"Values":[{
"Text":"A"
},
{
"Text":"B"
},
{
"Text":"C"
},
{
"Text":"D"
},
{
"Text":"E"
}]
}

Checking for read and write into another file. Output:

{"Values":[{"Text":"A"},{"Text":"B"},{"Text":"C"},{"Text":"D"},{"Text":"E"}]}

All good so far but I don't understand how to read the individual variables by indexnumber, like so:

Debug.Log("Values: " + newObject.Values[0]);

Which returns empty. How can I access these variables by index number?

Thanks in advance.

1 Answer 1

1

You're almost there!

Since your Valuesarray class has the Text variable, your code should call it:

    Debug.Log("Values: " + newObject.Values[0].Text);
    Debug.Log("Values: " + newObject.Values[1].Text);
    Debug.Log("Values: " + newObject.Values[2].Text);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot, it worked! I didn't expect this solution, but it's definitely helping me to develop the script further.
@Hieronymus Best of luck with your project. Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.