在C#

时间:2017-03-01 23:24:16

标签: c# json firebase firebase-realtime-database

所以,我有一个json文件,格式如下

{
  "-KeArK3V02mXYWx2OMWh" : {
    "Description" : "this is a description",
    "Location" : "Atlanta",
    "Name" : "Event One",
    "Time" : "2017-03-01T21:53:12.924645Z"
  },
  "-KeAtCNF_rmewZ_U3PpH" : {
    "Description" : "another description",
    "Location" : "Charlotte",
    "Name" : "Event Two",
    "Time" : "2017-03-01T22:01:25.603547Z"
  },
  "-KeAtd8CQW_EfH3Sw4YQ" : {
    "Description" : "description goes here",
    "Location" : "Toronto",
    "Name" : "Event Three",
    "Time" : "2017-03-01T22:03:19.3953859Z"
  }
}

我有一个名为Event的类,定义如下

class Event {
  public string Description { get; set; }
  public string Location { get; set; }
  public string Name { get; set; }
  public DateTime Time { get; set; }
}

我想通过这个并将每个子节点反序列化为Event对象,基本上将整个JSON反序列化为List< Event&gt ;.

问题是事件不在数组中,它们是另一个JSON对象的子节点。事实证明它并不像

那么简单
List<Event> elist = JsonConvert.DeserializeObject<List<Event>>(jsonResult);

我已经看到类似的问题询问了哪些项目是在JSON数组中组织的,我已经尝试了那里列出的解决方案,但它们只在它是一个实际数组时工作,而不是我在这里的结构。谷歌Firebase就是我在这里使用的,不幸的是它不支持JSON数组,所以我无法将数据包含在数组中。

我并不习惯JSON语法,所以我可能会遗漏一些非常明显的东西,但我完全被难倒了。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

你能尝试这种方法吗?这很直接

var str = @"{
'-KeArK3V02mXYWx2OMWh' : {
    'Description' : 'this is a description',
    'Location' : 'Atlanta',
    'Name' : 'Event One',
    'Time' : '2017-03-01T21:53:12.924645Z'
  },
  '-KeAtCNF_rmewZ_U3PpH' : {
    'Description' : 'another description',
    'Location' : 'Charlotte',
    'Name' : 'Event Two',
    'Time' : '2017-03-01T22:01:25.603547Z'
  },
  '-KeAtd8CQW_EfH3Sw4YQ' : {
    'Description' : 'description goes here',
    'Location' : 'Toronto',
    'Name' : 'Event Three',
    'Time' : '2017-03-01T22:03:19.3953859Z'
  }
}";
Dictionary<string, Event> elist = JsonConvert.DeserializeObject<Dictionary<string, Event>>(str);