【问题标题】:JSON return type from API call来自 API 调用的 JSON 返回类型
【发布时间】:2015-02-15 12:43:01
【问题描述】:

我正在制作一个使用 memes 的 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"
}

}

我得到的结果看起来像这样(注意 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;

        }

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 好的,我正在使用 JSON.Net 的 JObject 解析响应,它工作得很好。谢谢!
    猜你喜欢
    • 2019-05-27
    • 2017-05-30
    • 1970-01-01
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-20
    • 1970-01-01
    相关资源
    最近更新 更多