tonyy
tonyy

Reputation: 27

How do I get a JSON object from a webpage

New to C#. I have a URL https://osu.ppy.sh/beatmapsets/781509#osu/1642274 with multiple json objects but I want to retrieve only the object with id="json-beatmapset" from this URL. This is my current piece of code:

string url = @"https://osu.ppy.sh/beatmapsets/781509#osu/1642274";
var code = new WebClient().DownloadString(url);
Console.WriteLine(code);

And I want to be able to extract information (for example the title) from this one json object using this:

    dynamic dobj = JsonConvert.DeserializeObject<dynamic>(json);

    string title = dobj["title"].ToString();
    Console.WriteLine(title);

where json is the json object, which should print Black Rover (TV Size)

How do I get the json object from this url?

Upvotes: 0

Views: 175

Answers (1)

ThePerplexedOne
ThePerplexedOne

Reputation: 2950

As per my comment, you can use regular expressions to parse string data.

var json = Regex.Match(code, "<script id=\"json-beatmapset\".*?>(.*?)<\\/script>", RegexOptions.Singleline).Groups[1].Value;
dynamic dobj = JsonConvert.DeserializeObject<dynamic>(json);
string title = dobj["title"].ToString();
Console.WriteLine(title);

Upvotes: 1

Related Questions