【问题标题】:JSON parsing error when trying to use Face API尝试使用人脸 API 时出现 JSON 解析错误
【发布时间】:2019-04-13 22:04:27
【问题描述】:

我正在尝试通过 URL 地址从 Imgur 将照片发送到 Microsoft Face API,并从 Json 响应中获取人脸 ID,但是当我尝试运行代码时,我总是收到 JSON 解析错误。我不知道我做错了什么。

我试图通过 Postman 提出这个请求,那里一切正常,但在 c# 中它不起作用。

你能帮帮我吗?

    static void TryFunction()
    {
        string host = "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true";
        string subscriptionKey = "...";

        body = new System.Object[] { new { url = @"https://i.imgur.com/... .png" } };
        var requestBody = JsonConvert.SerializeObject(body);

        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage())
        {
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
            request.Method = HttpMethod.Post;
            request.RequestUri = new Uri(host);
            request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");

            var response = client.SendAsync(request).Result;
            var jsonResponse = response.Content.ReadAsStringAsync().Result;

            dynamic json = JsonConvert.DeserializeObject(jsonResponse);
            Console.WriteLine(jsonResponse);
        }
    }

{"error": {"code":"BadArgument", "message":"JSON 解析错误。"}}

C# 请求正文如下所示:

[{"url":"https://i.imgur.com/... .png"}]

而 Postman 请求正文如下所示:

{ "url": "https://i.imgur.com/... .png" }

【问题讨论】:

  • C# 请求和 Postman 请求有什么不同?您可以使用 Telerik 的 Fiddler 之类的工具来找出答案。唯一让我印象深刻的事情(不知道人脸 API)是:你是要传递一个数组还是一个对象?
  • 区别在于正文请求。这就是它的样子:[{"url":"https://i.imgur.com/... .png"}] 它应该是这样的:{ "url": "https://i.imgur.com/... .png" }

标签: c# json face-api


【解决方案1】:

根据您的评论,您需要一个对象,但会生成一个数组。这归结为以下代码行:

body = new System.Object[] { new { url = @"https://i.imgur.com/... .png" } };

这将创建一个包含单个项目的数组。你真正想要的只是一个项目:

body = new { url = @"https://i.imgur.com/... .png" };

注意,JSON 中的 [ ] 是一个数组,而 JSON 中的 { } 是一个对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-04
    • 2014-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多