【问题标题】:Getting images URL from a property in C#从 C# 中的属性获取图像 URL
【发布时间】:2021-12-31 01:03:19
【问题描述】:

我从一个网站获取 24 张图片 URL(8 张图片,每张图片有 3 种不同的尺寸,这就是 Web API 的工作方式,我无法更改)

我将它们作为 JSON 获取,然后使用牛顿软 JSON 将它们解析为 here 所示。

每个图像 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 
                }

【问题讨论】:

  • 请显示实际的json
  • 为什么有8堂课?

标签: c# json


【解决方案1】:

如果您使用 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.

【讨论】:

    【解决方案2】:

    请看下面的代码,这是读取属性的方法。

    帮助类读取属性

       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");
    

    【讨论】:

    • thx,它帮助了 2 个答案,帮助我无法检查两者的绿色标记:(
    猜你喜欢
    • 2018-05-25
    • 2010-10-30
    • 1970-01-01
    • 2014-12-26
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 2015-07-15
    • 2015-01-29
    相关资源
    最近更新 更多