JSON x,y coordinate List into Unity variable

Hello, I searched converting json array or lists into variable in Unity. But I couldn’t find any specific solutions for my problem. also I’m new and learning Unity.

what I want to know is how can I change the json string data into json file in Unity, and read the values from it.

{"frameSeq":1,"posCount":2,"frameIdx":22218,"positionList":[{"x":245,"y":5},{"x":255,"y":1
5}]}

this is the json data that I want to convert into json file, and use it to read the values that I want.

other things such as frameSeq, posCount is integer so there was no problem reading these.

But how can I manage the positionList?

the positionList values will be used to spawn and place objects in my game. and it will spawn multiple objects if there is more than one set of x,y coordinates.

class Data
{
    public int frameIdx;
    public int frameSeq;
    public int posCount;
    public List<Vector2> positionList;
}

public class Json_test : MonoBehaviour
{
    Data player = new Data() {frameSeq = 1, posCount = 2, frameIdx = 22218, positionList = new List<Vector2> { new Vector2(245, 5), new Vector2(255, 15) } };
   
    void Start()
    {
        string jsonData = JsonUtility.ToJson(player);

        Data Player2 = JsonUtility.FromJson<Data>(jsonData);
        print(Player2.frameSeq);
        print(Player2.frameIdx);
        print(Player2.posCount);
        print(Player2.positionList);
    }

Stuck with the problem of getting the correct values of positionList…

I want to use the x,y coordinate vaules maybe like positionList.x & positionList.y

is there solution for this?

sorry for asking topics that were discussed in the fourm multiple times, but I couldn’t find key solution for my project.

How are you verifying that the list doesn’t contain the correct data? Simply printing the list object won’t be much help, as List does not print the list content when using ToString. It would be better to do either one of the following:

var positionList = Player2.positionList;
for (int i = 0; i < positionList.Count; i++)
{
  Debug.Log(positionList[i]);
}
Debug.Log($"[{new System.Text.StringBuilder().AppendJoin(", ", Player2.positionList)}]");

The type you’re deserializing into, in this case your Data class, needs to have SerializableAttribute to follow Unity’s serialization rules.

2 Likes