2017-04-06 101 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++) {