Search code examples
c#jsonjson.netface-api

Deserializing JsonArray


I've written a code which calls an API which returns a Json Array which I have tired to deserialize using Json.net as below-

static async void MakeAnalysisRequest(string imageFilePath)
    {
        HttpClient client = new HttpClient();

        // Request headers.
        client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);

        // Request parameters. A third optional parameter is "details".
        string requestParameters = "returnFaceId=true";

        // Assemble the URI for the REST API Call.
        string uri = uriBase + "?" + requestParameters;

        HttpResponseMessage response;

        // Request body. Posts a locally stored JPEG image.
        byte[] byteData = GetImageAsByteArray(imageFilePath);

        using (ByteArrayContent content = new ByteArrayContent(byteData))
        {
            // This example uses content type "application/octet-stream".
            // The other content types you can use are "application/json" and "multipart/form-data".
            content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

            // Execute the REST API call.
            response = await client.PostAsync(uri, content);

            // Get the JSON response.
            string contentString = await response.Content.ReadAsStringAsync();

            // Display the JSON response.
            Console.WriteLine("\nResponse:\n");
            List<Facejson> obj=JsonConvert.DeserializeObject<List<Facejson>>(contentString);
            Console.WriteLine(obj[0].Face.faceId);
        }
    }

 public class Facejson
{
    [JsonProperty("face")]
    public Face Face { get; set; }
}

public class Face
{
    [JsonProperty("faceId")]
    public string faceId { get; set; }
}

The Api response Json is in the format

  [
   {
  "faceId": "f7eda569-4603-44b4-8add-cd73c6dec644",
  "faceRectangle": {
     "top": 131,
     "left": 177,
     "width": 162,
     "height": 162
    }
  },
  {
  "faceId": "f7eda569-4603-44b4-8add-cd73c6dec644",
  "faceRectangle": {
     "top": 131,
     "left": 177,
     "width": 162,
     "height": 162
    }
  } 
]

When I compile my code, the following error shows up

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.

in the line

Console.WriteLine(obj[0].Face.faceId);

I have declared the method "Face" but it shows that I have not. What am I doing wrong?

Edit- fixed Json and faulty code fixed as suggested.


Solution

  • You are deserializing a List<Face>, so to access one item on this list, you will have to use an index:

    Console.WriteLine( obj[0].Face.faceId );
    

    Or enumerate all results one-by-one:

    foreach ( var face in obj )
    {
       Console.WriteLine( face.Face.faceId );
    }
    

    Update

    You are deserializing a wrong type. Your JSON is directly a list of Face class instances, so the FaceJson type is not necessary:

    List<Face> obj = JsonConvert.DeserializeObject<List<Face>>(contentString);
    
    foreach ( var face in obj )
    {
       Console.WriteLine( face.faceId );
    }