【问题标题】:JSON to Array C#JSON 到数组 C#
【发布时间】: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 规则... 读取文件时总是捕获。所以不!

标签: c# json twitter


【解决方案1】:

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

类 world 和 worldData 还可以,但 world 类缺少 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);

关于异常的捕获:仅当您要对异常做一些明智的事情时才捕获异常。

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

这样的空捕获是无用的,只会妨碍调试。你可以和unchecked exceptions一起生活。

【讨论】:

  • 谢谢,所以该变量必须与 Json 变量相同。现在很高兴知道。我只是将类更改为 _world,因为它仅在初始化时需要。
猜你喜欢
  • 2014-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-16
  • 2015-05-26
  • 1970-01-01
相关资源
最近更新 更多