Mehmet
Mehmet

Reputation: 31

Get all Childrens of a JSON in C# using NewtonSoftJson

com User!

My Json:

I want to giveout all name -> username1 and username.

I used C# and newtonsoft.json

I hope somebody can help me. I tried it like this but it didnt work:

"kind":"UserList",
"data":{
   "children":[
      {
         "name":"test1",
         "author_flair_text":null,
         "mod_permissions":[
            "all"
         ],
         "date":1506648472.0,
         "rel_id":"rb_r8mbbr",
         "id":"t2_x6piz",
         "author_flair_css_class":null
      },
      {
         "name":"username2",
         "author_flair_text":null,
         "mod_permissions":[
            "all"
         ],
         "date":1553842373.0,
         "rel_id":"rb_18jmxnv",
         "id":"t2_a64nduq",
         "author_flair_css_class":null
      }
   ]
}
}


dynamic obj = JsonConvert.DeserializeObject<dynamic>(source);
             var mods = obj["data"]["children"].Children();
             foreach (var mod in mods)
             {
                 string modss = obj["data"]["children"][mods]["name"].ToString();
                 Console.WriteLine(modss);
             }

Upvotes: 0

Views: 52

Answers (1)

NGambit
NGambit

Reputation: 1181

You already have got a ‘mod’ as an object. All you need to do is access the “name” property of the ‘mod’.

dynamic obj = JsonConvert.DeserializeObject<dynamic>(source);
             var mods = obj["data"]["children"].Children();
             foreach (var mod in mods)
             {
                 string modss = mod["name"].ToString();
                 Console.WriteLine(modss);
             }

Note: The json you’ve pasted in the question is missing a starting ‘{‘ and without that it’s not valid.

Upvotes: 1

Related Questions