2014-11-01 82 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