2017-03-01 134 views
1

所以,我有以下列格式遍历在C#JSON对象(NOT数组)

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

JSON文件和我有定义了一类称为事件如下

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

,我想通过这个和反序列化的每个子节点到事件的对象,基本上都是反序列化JSON整成一个列表<事件>。

的问题是,该事件不是在一个阵列,他们是另一个JSON对象的子节点。因此,原来它不是那么简单

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

我见过其中的项目是在一个JSON阵列组织提出类似的问题,我尝试了那里列出的解决方案,但他们只当它是一个真正的工作数组,而不是我在这里的结构。谷歌Firebase是我在这里工作,不幸的是它不支持JSON数组,所以我没有办法在数组中包含项目。

我真的不使用JSON语法,所以我可能失去了一些东西真的很明显,但我完全难倒。

任何帮助将不胜感激。

+0

这可能会帮助你http://stackoverflow.com/questions/11132288/iterating-over-json-object-in-c-sharp –

+0

@JanakaDissanayake我今天早些时候看了那篇文章并尝试了他们使用的方法。不幸的是,这个例子是一个数组,对于这种情况 –

+0

我认为这将是相当有帮助的完整JSON文件是不行的,否则我们只是猜测。 – Enigmativity

回答

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

谢谢!它效果很好! –

+0

不客气! –

+0

这是用json对象填充elist字典吗?我正在尝试使用这种方法,但我不确定如何从字典中检索值。谢谢 –