JSON到数组C#

JSON到数组C#,c#,json,twitter,C#,Json,Twitter,仅使用Newtonsoft.json,尝试使用C#将json文件中的所有信息获取到数组中 namespace tslife { partial class game { world[] game_intro = _read_world<world>("intro"); //** other code **// public void update()

仅使用Newtonsoft.json,尝试使用C#将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和worldData正常,但世界类缺少属性
world

如果我将您的班级结构更改为:

public class worldData {
  public string Text { get; set; }
  public string Icon { get; set; }
  public int sectionID { get; set; }
} 

// notice I had to change your classname
// because membernames cannot be the same as their typename 
public class worldroot
{
        public worldData world { get; set; }
}
我可以在一个数组中反序列化json,该数组提供两个元素:

var l = JsonConvert.DeserializeObject<worldroot[]>(json);

这样的空捕获是无用的,只会妨碍调试。你可以接受。

你能试着替换
公共世界数据吗
使用公共worldData world{get;set;}并让我们知道发生了什么?我本来就有它,但仍然不起作用。你得到了一个空数组,对吗?你能摆脱那个空捕获吗?你不可能在类世界中有公共worldData世界{get;set;},因为它不编译。。。OOP IO规则。。。读取文件时始终捕获。所以不!谢谢,所以变量必须与Json变量相同。很高兴现在知道。我刚刚将类更改为_world,因为它只在初始化时需要。
var l = JsonConvert.DeserializeObject<worldroot[]>(json);
        try
        {
            var stream = File.OpenText("Application/story/"+level+".json"); 
            //Read the file              
            st = stream.ReadToEnd();
        }
        catch(SystemException e){}