简体   繁体   English

尝试使用Face API时出现JSON解析错误

[英]JSON parsing error when trying to use Face API

I'm trying to send photo from Imgur via URL adress to Microsoft Face API and get ID of face from Json response but when I try to run the code, I always get JSON parsing error. 我正在尝试通过URL地址从Imgur发送照片到Microsoft Face API并从Json响应中获取face的ID,但是当我尝试运行代码时,我总是得到JSON解析错误。 I have no idea what I am doing wrong. 我不知道我做错了什么。

I tried to make this request via Postman and everything is working fine there but in c# it just won't work. 我试图通过Postman提出这个请求,一切都很好,但在c#中它不会起作用。

Can you help me please? 你能帮我吗?

    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 parsing error."}} {“error”:{“code”:“BadArgument”,“message”:“JSON解析错误。”}}

The C# request body looks like this: C#请求体看起来像这样:

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

Whereas the Postman request body looks like this: 鉴于邮递员请求正文如下:

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

Based on your comment, you are expecting a single object, but generating an array. 根据您的评论,您期望一个对象,但生成一个数组。 This is down to the following line of code: 这取决于以下代码行:

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

This creates an array with a single item in it. 这将创建一个包含单个项目的数组。 What you actually want is just a single item: 你真正想要的只是一个项目:

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

Note that [ ] in JSON is an array, and { } in JSON is an object. 请注意,JSON中的[ ]是一个数组,JSON中的{ }是一个对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM