Search code examples
c#jsonjson.netreddit

Reddit search for key and the value in json data


i hope someone can help me. i'm a very beginner to json but i try to build a programm that loads all the posts from a subreddit trough the json file. I dont want to save it in a class so creating the classes from json is not an option as i found that not every subreddit has the same structure obviously.

as my example i use the /r/wallpaper https://www.reddit.com/r/wallpaper/hot.json?count=25

That is my current code but i always get a null result to dat2 when searchin in the JObject

var json = "";
using (WebClient client = new WebClient())
{
    json = client.DownloadString("https://www.reddit.com/r/wallpaper/hot.json?count=25");
    JObject data = JObject.Parse(json);

    string dat2 = data["url"].Value<string>();
}

How can i easily search for all value trough a key ? So for example i can get all the thumbnail from each post. I'm using Json.NET.


Solution

  • You need to find the children and loop through them. Each child has its own url.

    Sample code:

    var json = "";
    using (WebClient client = new WebClient())
    {
        json = client.DownloadString("https://www.reddit.com/r/wallpaper/hot.json?count=25");
        JObject data = JObject.Parse(json);
    
        var children = data["data"]["children"];
        for (var i = 0; i < children.Count(); i++)
        {
            Console.WriteLine(children[i]["data"]["url"]);
        }
    }