[英]How to retrieve a string value from a URL API using Json (C#)?
Hello Stackoverflow Masters!你好 Stackoverflow 大师!
I am trying to retrieve a random Chuck Norris joke from the API using JSON, but I am not sure how to retrieve the string value for value on the URL.我正在尝试使用 JSON 从 API 中检索一个随机的 Chuck Norris 笑话,但我不确定如何检索 URL 上值的字符串值。 This is what I was using, but I feel lost!这是我正在使用的,但我感到迷茫! Thank you for your kind help!谢谢你的热心帮助!
using (var client = new HttpClient())
{
joke = client.GetStringAsync(@"https://api.chucknorris.io/jokes/random").Result;
JObject result = JObject.Parse(joke);
foreach (var results in result)
{
string value = (string)result["value"];
}
}
MessageBox.Show(value);
There are some issues with the code provided (regarding best practices).提供的代码存在一些问题(关于最佳实践)。 The following would be better to call the API and get the response.以下最好调用API并获得响应。
You need to create a class to deserialize the json into:您需要创建一个类来将 json 反序列化为:
public class ChuckNorrisJoke {
public string Icon_Url { get; set; }
public string Id { get; set; }
public string Url { get; set; }
public string Value { get; set; }
}
Then you can send the request and deserialize the response:然后您可以发送请求并反序列化响应:
private static HttpClient httpClient = new HttpClient();
var uri = new Uri("https://api.chucknorris.io/jokes/random");
var reqMessage = new HttpRequestMessage(HttpMethod.Get, uri);
var response = httpClient.SendAsync(reqMessage);
var responseContent = await response.Content.ReadAsStringAsync();
var chuckNorrisJoke = JsonConvert.DeserializeObject<ChuckNorrisJoke>(responseContent);
This code will call the endpoint you provided with a GET request.此代码将调用您通过 GET 请求提供的端点。 Get the response, and read the content returned from the response, then turn the json in the response into the ChuckNorrisJoke object.获取响应,读取响应返回的内容,然后将响应中的json转成ChuckNorrisJoke对象。
After that, you can access the joke by using:之后,您可以使用以下方法访问笑话:
var joke = chuckNorrisJoke.Value;
Frist create a POCO class like:首先创建一个 POCO 类,如:
public class Random
{
public string[] categories { get; set; }
public DateTime created_at { get; set; }
public string icon_url { get; set; }
public string Id { get; set; }
public DateTime updated_at { get; set; }
public string url { get; set; }
public string value { get; set; }
}
then deserialize using Newtonsoft.Json nutget pack, you can add static function inside a class, this return a Random object type:然后使用 Newtonsoft.Json nutget pack 反序列化,您可以在类中添加静态函数,这将返回一个 Random 对象类型:
public static Random deserialize(string res)
{
return JsonConvert.DeserializeObject<Random>(res);
}
for using:用于:
using (var client = new HttpClient())
{
var joke = client.GetStringAsync(@"https://api.chucknorris.io/jokes/random").Result;
var returnedObject = Random.deserialize(joke);
string value = returnedObject.value;
// Console.WriteLine(value);
MessageBox.Show(value);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.