返回具有多个分支的api调用结果时出现问题



呼唤你的编码天才。我想弄清楚这件事,脸色发青。我正在调用一个公开的api来返回医生信息(https://npiregistry.cms.hhs.gov/api/?version=2.1&编号=1225185168&漂亮=开(我只是不知道如何到达较低的分支以返回我需要的信息。它可能看起来很方正,但我不知道我错过了什么。

提前谢谢。

这是我的代码(Core 6中的控制台应用程序(:

using System.Net.Http.Headers;
namespace ConsoleProgram
{
public class NpiRegistryModel
{
public string? First_name { get; set; }
public string? Last_name { get; set; }
public string? Postal_code { get; set; }
public string? City { get; set; }
public int? Number { get; set; }
}
public class Program
{
private const string URL = "https://npiregistry.cms.hhs.gov/api/";
private static string urlParameters = "?version=2.1&number=1225185168";
private static void Main(string[] args)
{
HttpClient client = new()
{
BaseAddress = new Uri(URL)
};
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync(urlParameters).Result;
if (response.IsSuccessStatusCode)
{
var dataObjects = response.Content.ReadAsAsync<IEnumerable<NpiRegistryModel>>().Result;
foreach (var d in dataObjects)
{
Console.WriteLine("Doctor: {0}, {1}", d.Last_name,d.First_name);
}
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
client.Dispose();
}
}
}

这是我得到的错误:System.AggregateExceptionHResult=0x80131500消息=出现一个或多个错误。(无法将当前JSON对象(例如{"name"value"}(反序列化为类型"System.Collections.Generic.IEnumerable1[ConsoleProgram.NpiRegistryModel]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'result_count', line 1, position 16.) Source=System.Private.CoreLib StackTrace: at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions) at System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification("位于System.Threading.Tasks.Task`1.get_Result((位于C:\Users\j###\source\Prototypes\TestApiCalls\HttpClientDemo\Program.cs:line 32 中的ConsoleProgram.Program.Main(String[]args(

此异常最初是在此调用堆栈中引发的:【外部代码】

内部异常1:JsonSerializationException:无法将当前JSON对象(例如{quot;name":quot;value"}(反序列化为类型"System.Collections.Generic.IEnumerable `1[ConsoleProgram.NpiRegistryModel]",因为该类型需要JSON数组(例如[1,2,3](才能正确反序列化。要修复此错误,请将JSON更改为JSON数组(例如[1,2,3](,或者更改反序列化的类型,使其成为可以从JSON对象反序列化的普通.NET类型(例如,不是像integer这样的基元类型,也不是像array或List这样的集合类型(。JsonObjectAttribute也可以添加到类型中,以强制它从JSON对象反序列化。路径"result_count",第1行,位置16。

首先必须解析json,然后才能提取需要的数据

using Newtonsoft.Json;
var json = response.Content.ReadAsStringAsync().Result;
var results = JObject.Parse(json)["results"][0];
NpiRegistryModel npiRegistryModel = results["basic"].ToObject<NpiRegistryModel>();
npiRegistryModel.PostalCode = (string) results["addresses"][0]["postal_code"];  
npiRegistryModel.City = (string) results["addresses"][0]["city"];
npiRegistryModel.Number = (int) results["number"];

public partial class NpiRegistryModel
{
[JsonProperty("first_name")]
public string FirstName { get; set; }
[JsonProperty("last_name")]
public string LastName { get; set; }
[JsonProperty("postal_code")]
public string? PostalCode { get; set; }

[JsonProperty("city")]
public string? City { get; set; }

[JsonProperty("number")]
public int? Number { get; set; }
}

最新更新