Reputation: 23
I'm making an app that uses Reddit's API to get posts from sub reddits
but every time the JSON I got had \" instead of "
I tried three different methods to download the JSON from Reddit's website, but every time it's filled with \" and my deserializer can' handle that
var json = get_json("https://www.reddit.com/r/" + "memes" + "/new.json?sort=new&limit=1");
string webData = json.Replace('\"', '"');
MessageBox.Show(webData, "");
NormalInput normal = JsonConvert.DeserializeObject<NormalInput>(webData);
public string get_json(string url)
{
Uri uri = new Uri(url);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = WebRequestMethods.Http.Get;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string output = reader.ReadToEnd();
response.Close();
return output;
}
I expect the output from the json.Replace() or get_json() to not have any \", but I'm getting them everywhere
Upvotes: 2
Views: 123
Reputation: 23521
Here is a complete working example using dynamic and a basic WebClient:
using System;
using Newtonsoft.Json;
using System.Net;
public class Program
{
public static void Main()
{
var client = new WebClient();
var url = "https://www.reddit.com/r/" + "memes" + "/new.json?sort=new&limit=1";
var json = client.DownloadString(url);
dynamic output = JsonConvert.DeserializeObject<dynamic>(json);
Console.WriteLine(output.data.children[0].data.title);
}
}
current output:
This meme is not dead!
To interact reddit, maybe you should rely on a C# reddit client library. Check nuget.
If you want to keep going with an homemade solution (for fun and learning), you can improve this quick answer by using HttpClient
instead of the old (but simple) WebClient
and switch from the dynamic usage of JsonConvert.DeserializeObject
to a real class (I wrote an answer to achieve that. Try it ^^). If your class NormalInput
matches the json, keep using it.
Upvotes: 4
Reputation: 90
I see that you try to download JSON from an URI. Using NewtonSoft is a good way to get json from URI.
Please take a look of this post : https://www.codeproject.com/Tips/397574/Use-Csharp-to-get-JSON-Data-from-the-Web-and-Map-i
Upvotes: 0