C#循环遍历json对象

时间:2017-11-26 15:23:00

标签: c# json

我是C#的初学者...我在C#中有一个跟随JSON对象(包含数组),我想循环遍历它,

{"maindepartment":[
{"id":0,"level":0,"label":"Employee Names","departments":[
    {"id":0,"level":1,"label":"IT","deparmentslevel1":[
        {"id":0,"level":2,"label":"dep1"},
        {"id":0,"level":2,"label":"dep2"}]},
    {"id":0,"level":1,"label":"dept","deparmentslevel1":[
        {"id":0,"level":2,"label":"dep3"},
        {"id":0,"level":2,"label":"dep4"}]}]},
{"id":0,"level":0,"label":"Employee Cities","cities":[
    {"id":0,"level":1,"label":""},
    {"id":0,"level":1,"label":"<p>New <strong>Jersey<\/strong><\/p>\n"},
    {"id":0,"level":1,"label":"<p>New & South - <strong>Whales<\/strong><\/p>\n"},              

{"id":0,"level":1,"label":"3223456"},
    {"id":0,"level":1,"label":"3465221"},
    {"id":0,"level":1,"label":"e"},
    {"id":0,"level":1,"label":"ee"},
    {"id":0,"level":1,"label":"ef"},
    {"id":0,"level":1,"label":"efg"},
    {"id":0,"level":1,"label":"eF!?"},
    {"id":0,"level":1,"label":"whales"},
    {"id":0,"level":1,"label":"new jersey"},
    {"id":0,"level":1,"label":"in"},
    {"id":0,"level":1,"label":"opq opq"},
    {"id":0,"level":1,"label":"ade"},
    {"id":0,"level":1,"label":"eert"},
    {"id":0,"level":1,"label":"meta"},
    {"id":0,"level":1,"label":"metadata"},
    {"id":0,"level":1,"label":"metadata from ajaja"},
    {"id":0,"level":1,"label":"testmets"},
    {"id":0,"level":1,"label":"p"},
    {"id":0,"level":1,"label":"jhonsons"},
    {"id":0,"level":1,"label":"demo"},
    {"id":0,"level":1,"label":"demo 123"},
    {"id":0,"level":1,"label":"demo Metadata 123"}]},
{"id":0,"level":0,"label"      :"Specific Terms","departments":[
    {"id":0,"level":1,"label":"demo"},
    {"id":0,"level":1,"label":"new maindepartment 1111"},
    {"id":0,"level":1,"label":"secret maindepartment"}]}]};

如何循环并获取内部元素的值?

1 个答案:

答案 0 :(得分:1)

首先,您必须将此JSON解析为C#类(或使用C#dynamic)。 为此,只需将您的JSON数据复制到this web site的文本框中,它将根据JSON数据格式生成C#类。

将它生成的课程带到你的项目中。

其次,您必须将JSON字符串数据解析为C#类。您可以通过以下方式完成:

YourClass data = Newtonsoft.Json.JsonConvert.DeserializeObject<YourClass>(jsonDataString);

然后你可以像往常那样迭代C#对象(在数据中)。