【发布时间】:2014-12-28 15:44:30
【问题描述】:
尝试使用 C# 仅使用 Newtonsoft.Json 将 json 文件中的所有信息获取到数组中。
namespace tslife
{
partial class game
{
world[] game_intro = _read_world<world>("intro");
//** other code **//
public void update()
{
//crashes: System.NullReferenceException: Object reference not set to an instance of an object
Console.WriteLine(game_intro[0].data.Text);
}
private static T[] _read_world<T>(string level)
{
var json_data = string.Empty;
string st = "";
try
{
var stream = File.OpenText("Application/story/"+level+".json");
//Read the file
st = stream.ReadToEnd();
}
catch(SystemException e){}
json_data = st;
//Console.WriteLine(json_data);
// if string with JSON data is not empty, deserialize it to class and return its instance
T[] dataObject = JsonConvert.DeserializeObject<T[]>(json_data);
return dataObject;
}
}
}
public class worldData {
public string Text { get; set; }
public string Icon { get; set; }
public int sectionID { get; set; }
}
public class world
{
public worldData data;
}
我不知道它是否是 json 的格式,但是我在搜索其他地方后被卡住了。
[{
"world":
{
"Text":"Hi",
"Icon":"image01.png",
"sectionID": 0
}
},
{
"world":
{
"Text":"Hey",
"Icon":"image02.png",
"sectionID": 1
}
}
]
【问题讨论】:
-
您可以尝试将
public worldData data;替换为public worldData world {get; set;}并告诉我们会发生什么吗? -
我原来有,还是不行。
-
你得到一个空数组,对吧?你能摆脱那个空的捕获吗?
-
你不可能有 public worldData world {get; set;} 在类世界中,因为那不会编译....
-
rene... OOP IO 规则... 读取文件时总是捕获。所以不!