【发布时间】:2021-02-19 18:35:23
【问题描述】:
这是我在 StackOverflow 上的第一篇文章,所以,如果这有点不妥,请见谅。
我最近一直在使用 JSON APIs,到目前为止一直很有趣,但是,我在使用 Mars Rover API 时遇到了一些问题。
我正在尝试获取 img_src 并在我调用它们时随机获取它们。所以,我会调用该方法,它会查找所有“img_src”,然后随机选择一个。
JSON:
{
"photos": [
{
"id": 102693,
"sol": 1000,
"camera": {
"id": 20,
"name": "FHAZ",
"rover_id": 5,
"full_name": "Front Hazard Avoidance Camera"
},
"img_src": "http://mars.jpl.nasa.gov/msl-raw-images/proj/msl/redops/ods/surface/sol/01000/opgs/edr/fcam/FLB_486265257EDR_F0481570FHAZ00323M_.JPG",
"earth_date": "2015-05-30",
"rover": {
"id": 5,
"name": "Curiosity",
"landing_date": "2012-08-06",
"launch_date": "2011-11-26",
"status": "active"
}
},
{
"id": 102694,
"sol": 1000,
"camera": {
"id": 20,
"name": "FHAZ",
"rover_id": 5,
"full_name": "Front Hazard Avoidance Camera"
},
"img_src": "http://mars.jpl.nasa.gov/msl-raw-images/proj/msl/redops/ods/surface/sol/01000/opgs/edr/fcam/FRB_486265257EDR_F0481570FHAZ00323M_.JPG",
"earth_date": "2015-05-30",
"rover": {
"id": 5,
"name": "Curiosity",
"landing_date": "2012-08-06",
"launch_date": "2011-11-26",
"status": "active"
}
},
上面的 JSON 是它的格式,它只是以这种格式一遍又一遍地重复(855 次)。我想要得到的只是“earth_date”和“img_src”
我的代码:
public static async Task<MarsRoverImagesModel> getMarsRoverImagesAsync()
{
string url = "https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol=1000&api_key=API_KEY";
using (HttpResponseMessage response = await API_Stuff.APIHelper.APIClient.GetAsync(url))
{
if (response.IsSuccessStatusCode)
{
// Don't know what to do here to get what I need
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
}
“ApiClient”:
public class APIHelper
{
public static HttpClient APIClient { get; set; }
public static void InitialiseClient()
{
APIClient = new HttpClient();
APIClient.DefaultRequestHeaders.Accept.Clear();
APIClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
}
主要型号:
class MarsRoverImagesModel
{
public string img_src { get; set; }
public string earth_date { get; set; }
}
然后是根模型:
class MarsRoverRootModel
{
public MarsRoverImagesModel photos { get; set; }
}
抱歉,这有点啰嗦,但我真的很感谢我能得到的任何帮助,因为这几天一直困扰着我。
谢谢!
【问题讨论】:
-
你怎么了?
-
这可能会有所帮助:stackoverflow.com/q/57066632/578411 假设您已经可以访问响应正文。或者更好:stackoverflow.com/questions/37642984
标签: c# json dotnet-httpclient