API调用的JSON返回类型

时间:2015-02-15 12:43:02

标签: c# asp.net .net json http

我正在制作一个使用模因的c#asp.net网站。我正在使用HttpClient.PostAsync(url,FormUrlEncodedContent)对imgflip.com进行API调用 - 这将返回一个JSON对象,其中包含指向其服务器上生成的meme的链接。在API文档中,成功的结果如下所示:

{
"success": true,
"data": {
    "url": "http://i.imgflip.com/123abc.jpg",
    "page_url": "https://imgflip.com/i/123abc"
}

}

我得到的结果看起来像这样(请注意网址中的转发反斜杠):

{"success":true,"data":{"url":"http:\/\/i.imgflip.com\/ho1uk.jpg","page_url":"https:\/\/imgflip.com\/i\/ho1uk"}} 

我需要解析反斜杠并且网址工作得很好 - 我为什么要把它们放在第一位?解析它们是直截了当的,但它们在那里的事实让我觉得我的要求一定是错的。以下是我用来获取响应的方法:

        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;

        }

我得到了正确的响应(差不多)并在内容标题类型中指定了正确的内容类型 - 为什么我的返回对象有反斜杠的想法?

1 个答案:

答案 0 :(得分:2)

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()或正则表达式。