我编写了一个调用 API 的代码,该 API 返回一个 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
}
}
]
当我编译我的代码时,出现以下错误
未处理的异常:System.NullReferenceException:对象引用未设置为对象的实例。
在行中
Console.WriteLine(obj[0].Face.faceId);
我已经声明了方法“Face”,但它表明我没有。我究竟做错了什么?
Edit-fixed Json 和错误代码按建议修复。