使用url的json输入,反序列化为c&;从web API检索值
本文关键字:amp web API 检索 json url 输入 反序列化 使用 | 更新日期: 2023-09-27 17:59:28
我一直在努力找出特定场景的语法。
场景:当我在URL中给定JSON字符串作为参数时,我希望URL使用API,并根据给定的输入从该API检索详细信息。
我的项目需要反序列化为c#,所以我也使用了JSON.NET。假设:输入为-配置文件id:123456789
输出应该使用与该Pid和显示相关的详细信息。url中给定的i/p:https://www.docscores.com/widget/api/org-profile/demo-health/npi/123456789
预期o/p:json字符串
我一直在做的是:
string url = "https://www.docscores.com/widget/api/org-profile/demo-health/npi/?profile-id=ShowProfile";
string data = GET(url);
dynamic jsonDe = JsonConvert.DeserializeObject(data);
var phyRatings = Convert.ToString(jsonDe.profile.averageRating);
Console.WriteLine(phyRatings);
public string ShowProfile(string pid)
{
}
public static string GET(string url)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string data = reader.ReadToEnd();
reader.Close();
stream.Close();
return data;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return null;
}
因此,当我在url中以123456789
的形式传递配置文件id时,我希望语法使用此配置文件id 提取其他信息
我完全搞不懂C#中的语法。如何传递参数并在ShowProfile函数内部进行编写?我到处找,但找不到正确的语法。
有人能告诉我这样做是否正确吗?
要将123456789
作为配置文件ID传递,只需将其连接到URL字符串中即可。所以你可能有
public string ShowProfile(string pid)
{
ProfileInfo info = GET(pid);
// Do what you want with the info here.
}
public static ProfileInfo GET(int profileId)
{
try
// Note this ends in "=" now.
string basePath = "/widget/api/org-profile/demo-health/npi/?profile-id=";
string path = basePath + profileId.ToString();
//...
ProfileInfo
将是您的自定义类,以匹配JSON结构。
然后,为了反序列化结果,在GET()
方法中,您可以尝试使用Microsoft.AspNet.WebApi.Client
NuGet包中的HttpClient
调用服务,然后将其直接读取到C#对象中,该对象的结构映射到您获得的JSON响应(请参阅下面的示例)。然后,您的GET()
方法可以返回该对象,然后ShowProfile()
方法从该C#对象读取您想要的属性将是微不足道的。
public static ProfileInfo GET(int profileId)
{
try
{
// Note this ends in "=" now.
string basePath = "/widget/api/org-profile/demo-health/npi/?profile-id=";
string path = basePath + profileId.ToString();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://www.docscores.com");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
ProfileInfo info = await response.Content.ReadAsAsync<ProfileInfo>();
return info;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return null;
}
MSDN上的更多代码和信息:在ASP.NET Web API 2(C#)中从.NET客户端调用Web API