我正在制作一个使用模因的 c# asp.net 网站。我正在使用 HttpClient.PostAsync(url, FormUrlEncodedContent) 对 imgflip.com 进行 API 调用 - 这将返回一个 JSON 对象,其中包含指向其服务器上生成的模因的链接。在 API 文档中,成功的结果如下所示:
{
"success": true,
"data": {
"url": "http://i.imgflip.com/123abc.jpg",
"page_url": "https://imgflip.com/i/123abc"
}
我得到的结果看起来像这样(注意 url 中的正向 和 反斜杠):
{"success":true,"data":{"url":"http:\/\/i.imgflip.com\/ho1uk.jpg","page_url":"https:\/\/imgflip.com\/i\/ho1uk"}}
我需要解析反斜杠并且 url 工作正常 - 为什么我首先得到它们?解析它们很简单,但它们在那里的事实让我觉得我的请求一定有问题。这是我用来获取响应的方法:
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;
}
我(几乎)得到了正确的响应并在内容 header 类型中指定了正确的内容类型 - 知道为什么我返回的对象有反斜杠吗?
最佳答案
JSON 规范将正斜杠定义为可以选择转义的字符。
您收到的是有效的 JSON 文档。解决方法很简单。使用 JSON 解析器(参见 https://stackoverflow.com/a/9573161 )。
您不应该关心结构化数据的序列化表示(这就是 JSON - 结构化数据的序列化格式)。您可能会收到这个:
{
"\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"
}
}
来自服务器,它仍然与 imgflip API 文档中所述相同。
只需使用解析器,它就会做正确的事情。不要尝试在 JSON 上使用 String.IndexOf()
或正则表达式。
关于c# - API 调用的 JSON 返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28526144/