反序列化 JsonArray

Deserializing JsonArray

我写了一个代码,它调用一个 API,其中 returns 一个 Json 数组,我已经厌倦了使用 Json.net 反序列化,如下所示-

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; }
}

Api 响应 Json 的格式为

  [
   {
  "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
    }
  } 
]

当我编译我的代码时,出现以下错误

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

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

我已经声明了方法 "Face" 但它表明我没有。我做错了什么?

编辑 - 已修复 Json 并按照建议修复了错误代码。

您正在反序列化 List<Face>,因此要访问此列表中的一项,您将必须使用索引:

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

或枚举所有结果one-by-one:

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

更新

您正在反序列化错误的类型。您的 JSON 直接是 Face class 个实例的列表,因此 FaceJson 类型不是必需的:

List<Face> obj = JsonConvert.DeserializeObject<List<Face>>(contentString);

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

JSON 您分享的字符串不正确。请检查此 fiddle.

[
  {
    "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
    }
  }
]

你还在反序列化一个 List<Face> ,你只能使用索引访问它。

更新

您需要反序列化 List<Face> 而不是单个 Face class。它会解决你的问题。