简体   繁体   English

在 C# 中迭代​​ JSON 对象(不是数组)

[英]Iterating over a JSON object (NOT an array) in C#

So, I have a json file in the following format所以,我有一个以下格式的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"
  }
}

and I have a class called Event that is defined as follows我有一个名为 Event 的类,其定义如下

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

and I'd like to go through this and deserialize each of the child nodes into Event objects, basically deserializing the entire JSON into a List<Event>.我想通过这个并将每个子节点反序列化为事件对象,基本上将整个 JSON 反序列化为 List<Event>。

The issue is that the events aren't in an array, they're child nodes of another JSON object.问题是事件不在数组中,它们是另一个 JSON 对象的子节点。 So it turns out it's not as simple as所以事实证明它不是那么简单

List<Event> elist = JsonConvert.DeserializeObject<List<Event>>(jsonResult);

I've seen similar questions asked where the items were organized in a JSON array, and I've tried the solutions listed there but they only work when it's an actual array, not the structure I have here.我看到过类似的问题,询问项目在 JSON 数组中的组织位置,我尝试了那里列出的解决方案,但它们仅在实际数组时才有效,而不是我在这里的结构。 Google Firebase is what I'm working with here and unfortunately it doesn't support JSON arrays, so I have no way of containing the items in an array instead.我在这里使用的是 Google Firebase,不幸的是它不支持 JSON 数组,因此我无法将这些项目包含在数组中。

I'm not really used to JSON syntax so I might be missing something really obvious here, but I'm completely stumped.我不太习惯 JSON 语法,所以我可能在这里遗漏了一些非常明显的东西,但我完全被难住了。

Any help would be greatly appreciated.任何帮助将不胜感激。

Can you try this approach?你能试试这个方法吗? It's pretty straight forward这很直接

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM