I take from a website 24images URLs(8images and each image has 3 different sizes this is how the web API works and I cannot change it)
I get those as JSON and I parse them as shown here using newton soft JSON.
Each image URL is stored in property in the same class as its different size images
and different images are stored in other classes
so there are 8classes containing 3 properties which contains image url
I am trying to get 1image url from each class
I am trying to use reflection but since these classes has different names, it is hard to do it (for me at least)
I have came this far
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
}
CodePudding user response:
If you are using Newtonsoft JSON library - then you can use the JObject class, it's an abstraction for any JSON object.
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.
CodePudding user response:
Please see the code below, this is how you can read properties.
Helper class to read properties
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));
}
}
}
}
}
Sample API data
var photos = new Photos
{
_1 = new __1() { _3 = "http://www.google3.com", _2 = "http://www.google2.com", _0 = "http://www.google0.com" },
};
Reading the data
Helper.GetDataByProperty(photos.GetType(), photos._1, "_1");