Search code examples
c#jsonface-api

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. 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.

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."}}

The C# request body looks like this:

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

Whereas the Postman request body looks like this:

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

Solution

  • 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.