访问 C# 中的嵌套对象

问题描述 投票:0回答:1

我正在尝试通过 Google Books API 访问我的对象的特定属性。内容被反序列化为两个 POCO 以访问嵌套对象。我被困在访问

volumeInfo
的属性来收集标题、作者、图像等信息。

//POCOs
public class GBAModel1
{
    public List<GBAModel2> items { get; set; }
}
public class GBAModel2
{
    public string id { get; set; }
    public string selfLink { get; set; }
    public Object volumeInfo { get; set; }

}
//REPOSITORY
public async Task<List<GBAModel2>> GetBooksFromApi()
{
    string testUrl = "https://www.googleapis.com/books/v1/volumes?q=jujutsu+kaisen+isbn=%229781974733767%22+inauthor=Gege";

    using (HttpResponseMessage response = await ApiHelper.ApiClient.GetAsync(testUrl))
    {
        if (response.IsSuccessStatusCode)
        {
            GBAModel1 results = await response.Content.ReadFromJsonAsync<GBAModel1>();

            return results.items;
        } else
        {
            throw new Exception(response.ReasonPhrase);
        }
    }
}
//CONTROLLER
[HttpGet("/booksApi")]
public async Task<IActionResult> GetBooks()
{
    var testResult= await _bookAction.GetBooksFromApi();
    var testAccess = testResult[0].volumeInfo;
    return Ok(testAccess);
}
//EXAMPLE JSON
{
  "kind": "books#volumes",
  "totalItems": 1,
  "items": [
    {
      "kind": "books#volume",
      "id": "cltJEAAAQBAJ",
      "etag": "cWfbxxKUP7w",
      "selfLink": "https://www.googleapis.com/books/v1/volumes/cltJEAAAQBAJ",
      "volumeInfo": {
        "title": "Jujutsu Kaisen, Vol. 17",
        "subtitle": "Perfect Preparation",
        "authors": [
          "Gege Akutami"
        ],
        "publisher": "VIZ Media LLC",
        "publishedDate": "2022-08-16",
        "description": "Hunted down by Okkotsu and on the brink of death, Itadori recalls a troubling family scene from his past. But why is the former form of Noritoshi Kamo there? As the sorcerers begin to take action toward suppressing the lethal culling game, Maki pays the Zen’in clan a visit... -- VIZ Media",
        "industryIdentifiers": [
          {
            "type": "ISBN_13",
            "identifier": "9781974733767"
          }
        ],
        "imageLinks": {
          "smallThumbnail": "http://books.google.com/books/content?id=cltJEAAAQBAJ&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
          "thumbnail": "http://books.google.com/books/content?id=cltJEAAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
        },
        "language": "en",
      },
    }
  ]
}

我尝试使用像

var testAccess = testResult[0].volumeInfo.title
这样的点属性,但给了我一个 CS1061:

“object”不包含“title”的定义,并且找不到接受“object”类型的第一个参数的可访问扩展方法“title”(您是否缺少 using 指令或程序集引用?)。

还尝试通过方法获取标题:

var testAccess = testResult[0].volumeInfo;
var try2 = testAccess .GetType()
          .GetProperty("title")
          .GetValue(this, null);
return Ok(try2);

...但是错误是

未将对象引用设置为对象的实例。

我怎样才能正确访问这个对象?

c# json asp.net-mvc object
1个回答
0
投票

在 C# 中,解决此类问题最惯用的方法是定义 DTO 来包含所需的属性:

public class VolumeInfo
{
    public string title { get; set; }
    public string subtitle { get; set; }
    public List<string> authors { get; set; }
    public string publisher { get; set; }
    public string publishedDate { get; set; }
    public string description { get; set; }
    public List<IndustryIdentifier> industryIdentifiers { get; set; }
    public ImageLinks imageLinks { get; set; }
    public string language { get; set; }
}

然后更新

volumeInfo
GBAModel2
属性:

public class GBAModel2
{
    public string id { get; set; }
    public string selfLink { get; set; }
    public VolumeInfo volumeInfo { get; set; }
}

然后你可以写

testResult.items[0].volumeInfo.title

如果您不想创建所有这些 DTO,您还可以 直接使用 JSON AST

© www.soinside.com 2019 - 2024. All rights reserved.