Calling out to you coding genius' out there. I'm blue in the face trying to figure this on out. I'm calling a publicly exposed api to return doctors information (https://npiregistry.cms.hhs.gov/api/?version=2.1&number=1225185168&pretty=on) and I just can't figure out how to reach the lower branches to return back the info I need. It's probably looking square in the eye but I have no idea what I'm missing.
Thanks in advance.
Here's my code (console app in 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();
}
}
}
Here's the error I'm getting:
System.AggregateException
HResult=0x80131500
Message=One or more errors occurred. (Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type '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.Task
1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task`1.get_Result()
at ConsoleProgram.Program.Main(String[] args) in C:\Users\j####\source\Prototypes\TestApiCalls\HttpClientDemo\Program.cs:line 32
This exception was originally thrown at this call stack: [External Code]
Inner Exception 1: JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.IEnumerable`1[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) 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.
CodePudding user response:
you have to parse your json at first, after this you can extract the data you need
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; }
}