2014-11-01 64 views
2

尝试从仅使用Newtonsoft.Json的C#将所有信息从json文件转换为数组。JSON到数组C#

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

你可以尝试更换'公共worldData数据;'与公共worldData世界{get;设置;}'让我们知道会发生什么? – rene 2014-11-01 13:14:50

+0

我原来是这样,仍然没有工作。 – 2014-11-01 13:17:56

+0

你得到一个空的数组,对吧?你能摆脱那空空的渔获吗? – rene 2014-11-01 13:19:33

回答

0

在没有注释的序列化和反序列化中,成员名称需要与您的JSON结构相匹配。

世界级和世界级的数据都是好的,但是世界级的数据库缺少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阵列中的whicjh给了我两个元素:

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

而且对异常的醒目:仅捕获如果你打算对他们做一些明智的事情,那就是例外。

 try 
     { 
      var stream = File.OpenText("Application/story/"+level+".json"); 
      //Read the file    
      st = stream.ReadToEnd(); 
     } 
     catch(SystemException e){} 

这样的空渔获量是无用的,只有在调试阻碍。你可以住在unchecked exceptions

+0

谢谢,所以变量必须与Json变量相同。现在很高兴知道。我只是将该类更改为_world,因为它仅在初始化时需要。 – 2014-11-01 13:48:59