![](/img/trans.png)
[英]How to Deserialize a JSON Array from Web API in UPW C#?
[英]Consuming json input from url ,deserialize into c# & retrieve values from web API
我一直在尝试找出特定场景的语法。
场景:当我在URL中提供JSON字符串作为参数时,我希望URL根据给定的输入使用API并从该API检索详细信息。
我的项目需要反序列化到c#中,所以我同样使用JSON.NET。 说:输入为-Profile-id: 123456789
输出应使用与该Pid和显示有关的详细信息。 网址中给出的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中将profile-id传递为123456789
时,我希望语法使用此Profile-id提取其他信息
我完全对C#中的语法感到困惑。 如何传递参数并在ShowProfile函数中编写? 我到处搜索,但找不到正确的语法。
有人可以告诉我这样做是否正确吗?
编辑:听起来你在这里有两个问题。 第一个是如何在URL中传递Profile-Id,第二个是如何将JSON结果反序列化为C#对象。 但是请让我知道我是否误会了。
要将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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.