2017-04-06 100 views
0

我想根據我的json文件填充3個列表。從json文件填充列表

目標是從json文件加載數據,分配給我的列表,以便我可以添加/修改這些值,然後將它們重新保存到json文件中。

不過似乎有一個問題,這條線

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

特別道具。

我將不勝感激關於如何填充我的水平列表和修改的解決方案!

這是我的JSON結構

[ 
    { 
    "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 ] 
     } 
    ] 
    } 
] 

這是我的全部代碼

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; 
    } 
} 
+0

把你的JSON文件[這裏](http://json2csharp.com/),它會告訴你什麼是你的JSON結構應看起來像。現在,看看如何閱讀Unity中的json的答案。 – Programmer

回答

0

一個問題我看到的是,你在裏面初始化您最初的for循環來填充你的等級列表中級別列表。這會使您的level變量在每次迭代開始時重新初始化爲新的空列表。

嘗試移動線:List<Level> level = new List<Level>();

前行: for(int i = 0; i < levelsJson.Count; i++) {