0

I'm trying to populate 3 lists according to my json file.

The goal is to load data from the json file, assign to my lists so that i can add/modify the values and then re-save them to the json file.

However there seems to be a problem with this line

level.Add(new Level(i, (string)levelsJson[i]["name"]), props );

specifically the props.

I would greatly appreciate a solution on how to populate my levels list and modify!

this is my json structure

[
  {
    "id": 0,
    "name": "Greatest level",
    "props": [
      {
        "name": "stone",
        "position": [ 4, 2 ]
      },
      {
        "name": "tree",
        "position": [ 1, 7 ]
      }
    ]
  },
  {
    "id": 1,
    "name": "shitty level",
    "props": [
      {
        "name": "stone",
        "position": [ 2, -5 ]
      },
      {
        "name": "tree",
        "position": [ 15, 2 ]
      }
    ]
  }
]

This is my entire code

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

public class json : MonoBehaviour {

    private List<Levels> levels = new List<Levels>();
    private JsonData levelsJson;

    void Start () {
        LoadLevels();
    }

    void LoadLevels() {
        levelsJson = JsonMapper.ToObject(File.ReadAllText(Application.dataPath + "/StreamingAssets/Levels.json"));

        //This is where im trying to populate the lists
        for(int i = 0; i < levelsJson.Count; i++) {
        List<Level> level = new List<Level>();
        List<Prop> props = new List<Prop>();
        for(int prop = 0; prop < levelsJson[i]["props"].Count; prop++) {
            props.Add(new Prop((string)levelsJson[i]["props"]["name"], new int[] { (int)levelsJson[i]["props"]["position"][0], (int)levelsJson[i]["props"]["position"][1]}));
        }
        level.Add(new Level(i, (string)levelsJson[i]["name"]), props );
    }

}

public class Levels {
    public Level[] levels;

    public Levels(Level[] l) {
        levels = l;
    }
}

public class Level {
    public int id;
    public string name;
    public Prop[] props;

    public Level(int i, string n, Prop[] p) {
        id = i;
        name = n;
        props = p;
    }
}

public class Prop {
    public string name;
    public int[] position;

    public Prop(string n, int[] p) {
        name = n;
        position = p;
    }
}
Glutch
  • 662
  • 1
  • 6
  • 19
  • Put your json file [here](http://json2csharp.com/) and it will show you what your json structure should look like. Now, look at the answer for how to read json in Unity. – Programmer Apr 06 '17 at 02:19

1 Answers1

0

One issue I see is that you're initializing your Level list inside of your initial for loop to populate your Level list. This will cause your level variable to be re-initialized to a new empty list at the start of each iteration.

Try moving the line: List<Level> level = new List<Level>();

before the line: for(int i = 0; i < levelsJson.Count; i++) {

JSarwer
  • 313
  • 2
  • 16