简体   繁体   中英

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

So, I have a json file in the following format

{
  "-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

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>.

The issue is that the events aren't in an array, they're child nodes of another JSON object. 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. 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.

I'm not really used to JSON syntax so I might be missing something really obvious here, but I'm completely stumped.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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