我從網站上獲取 24 個影像 URL(8 個影像,每個影像有 3 個不同的大小,這是 Web API 的作業方式,我無法更改它)
我得到那些為JSON和我分析他們如這里使用牛頓軟JSON。
每個影像 URL 都存盤在與其不同大小的影像相同的類中的屬性中
并且不同的影像存盤在其他類中
所以有 8 個類包含 3 個屬性,其中包含影像 url
我正在嘗試從每個類中獲取 1 個影像 url
我正在嘗試使用反射,但由于這些類具有不同的名稱,因此很難做到(至少對我而言)
我已經走了這么遠
PropertyInfo[] properties = typeof(Photos).GetProperties();
foreach (PropertyInfo property in properties)
{
object a = property.GetValue(mm);
//I cannot use a._1 or a._2 because it is not an instance of the class I want I also cannot convert it since the class names are not the same
}
uj5u.com熱心網友回復:
如果您使用 Newtonsoft JSON 庫 - 那么您可以使用 JObject 類,它是任何 JSON 物件的抽象。
var uri = new Uri("Your API request URL");
using var client = new HttpClient();
var response = await client.GetAsync(uri);
var data = await response.Content.ReadAsStringAsync();
var jObject = JObject.Parse(data);
var img1 = jObject["_1"];
var img2 = jObject["_2"];
//And so on.
uj5u.com熱心網友回復:
請參閱下面的代碼,這是您讀取屬性的方式。
讀取屬性的輔助類
public static class Helper
{
public static void GetDataByProperty(Type photosType, object photoObject, string propertyNameToRead)
{
foreach (PropertyInfo photoProperty in photosType.GetProperties())
{
if (photoProperty.Name == propertyNameToRead)
{
foreach (var urlProperty in photoProperty.PropertyType.GetProperties())
{
Console.WriteLine(urlProperty.GetValue(photoObject));
}
}
}
}
}
示例 API 資料
var photos = new Photos
{
_1 = new __1() { _3 = "http://www.google3.com", _2 = "http://www.google2.com", _0 = "http://www.google0.com" },
};
讀取資料
Helper.GetDataByProperty(photos.GetType(), photos._1, "_1");
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/361542.html
下一篇:如何將引數輸入用于物件參考?
