Reputation: 1355
I am making a c# asp.net website which uses memes. I am making an API call to imgflip.com using HttpClient.PostAsync(url, FormUrlEncodedContent) - this returns a JSON object which includes a link to the generated meme on their server. In the API documentation the successful result looks like this:
{
"success": true,
"data": {
"url": "http://i.imgflip.com/123abc.jpg",
"page_url": "https://imgflip.com/i/123abc"
}
}
I am getting a result which looks like this (note the forward and back slashes in the url):
{"success":true,"data":{"url":"http:\/\/i.imgflip.com\/ho1uk.jpg","page_url":"https:\/\/imgflip.com\/i\/ho1uk"}}
I need to parse out the backslashes and the url works fine - why am I getting them in the first place? Parsing them out is straightforward but the the fact they are there makes me think something must be wrong with my request. Here is the method I am using to get the response:
public async Task<string> GetReponseAsString(string templateID, string userName, string password, string topText, string bottomText) //non-optional parameters
{
string postURL = "https://api.imgflip.com/caption_image";
var formContent = new FormUrlEncodedContent(new[]{
new KeyValuePair<string, string>("template_id", templateID),
new KeyValuePair<string, string>("username", userName),
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("text0", topText),
new KeyValuePair<string, string>("text1", bottomText)
});
HttpClient client = new HttpClient();
var response = await client.PostAsync(postURL, formContent);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return response.Content.ReadAsStringAsync().Result;
}
I am getting the right response (almost) and specifying the proper content type in the content header type - any ideas why my returned object has the backslashes?
Upvotes: 3
Views: 1683
Reputation: 338406
The JSON specification defines the forward slash as a character that can optionally be escaped.
What you receive is a valid JSON document. The solution is simple. Use a JSON parser (see https://stackoverflow.com/a/9573161).
You should not care about the serialized representation of structured data (that's what JSON is - a serialization format for structured data). You could receive this:
{
"\u0073\u0075\u0063\u0063\u0065\u0073\u0073":true,
"\u0064\u0061\u0074\u0061": {
"\u0075\u0072\u006c":"\u0068\u0074\u0074\u0070:\/\/\u0069\u002e\u0069\u006d\u0067\u0066\u006c\u0069\u0070\u002e\u0063\u006f\u006d\/\u0068\u006f1\u0075\u006b\u002e\u006a\u0070\u0067",
"\u0070\u0061\u0067\u0065_\u0075\u0072\u006c":"\u0068\u0074\u0074\u0070\u0073:\/\/\u0069\u006d\u0067\u0066\u006c\u0069\u0070\u002e\u0063\u006f\u006d\/\u0069\/\u0068\u006f1\u0075\u006b"
}
}
from the server and it would still be the same thing as stated in the imgflip API documentation.
Just use a parser, it will do the right thing. Don't attempt to work with String.IndexOf()
or regular expressions on JSON.
Upvotes: 2