对于大量的代码,我表示歉意,但是对于问题的上下文来说,这是必要的。我面临着一个我无法解决的有趣的难题。我正在尝试从名为Repository的模型中访问信息。存储库包含嵌套类和列表,如下所示:
{
public User User { get; set; }
}
public class User
{
public PinnedItems PinnedItems { get; set; }
}
public class PinnedItems
{
public List<Nodes> Nodes { get; set; }
}
public class Nodes
{
public string Name { get; set; }
public string Description { get; set; }
public string Url { get; set; }
public RepositoryTopics RepositoryTopics { get; set; }
}
public class RepositoryTopics
{
public List<TopicNodes> Nodes { get; set; }
}
public class TopicNodes
{
public Topic Topic { get; set; }
}
public class Topic
{
public string Name { get; set; }
}我在web控制器中有以下方法。它负责使用graphql抓取我的github存储库。此方法如下所示:
{
var request = new GraphQLHttpRequest
{
Query = @"query($username: String!){
user(login: $username) {
pinnedItems(first: 6, types: REPOSITORY) {
nodes {
... on Repository {
name
description
url
repositoryTopics(first:6){
nodes{
topic{
name
}
}
}
}
}
}
}
}
",
Variables = new
{
username = _configuration.GetSection("GithubUserName").Value
}
};
var graphQlResponse = await CreateClient().SendQueryAsync<Repository>(request);
var repo = new Repository
{
User = graphQlResponse.Data.User
};
return Ok(repo);
}回购是一种储藏室。这是JSON的一个示例,它是在swagger中测试控制器后返回的。
"pinnedItems": {
"nodes": [
{
"name": "personal-website",
"description": "My personal website",
"url": "https://github.com/personal-website",
"repositoryTopics": {
"nodes": [
{
"topic": {
"name": "blazor-webassembly"
}
},
{
"topic": {
"name": "web-api"
}
},
{
"topic": {
"name": "contentful-api"
}
},
{
"topic": {
"name": "contentful"
}
}
]
}
}我使用以下方法访问blazor组件中的代码:
Repository SoftwareRepos = new Repository();
protected async override Task OnInitializedAsync()
{
SoftwareRepos = await graphQLquery.GetRepositories();
}
}一些示例代码(如这类代码)可以将项目列表作为名称。
@foreach(var name in SoftwareRepos.User.PinnedItems.Nodes.Select(x => x.Name).ToArray())
{
@name
}
PRINTS OUT: name, name, name, name理想情况下,我想要这样的东西:
Project One, Description, URL, html, css, react, javascript (a list of tags)
我很难构建LINQ查询来访问这些嵌套信息(特别是repositoryTopic -> TopicNodes -> Nodes -> Topics -> Name )。我正在寻求关于如何处理这种情况的建议,或者可能是一些替代我正在做的事情的解决方案,因为我怀疑我在这里有点超出了我的深度。我使用graphql.client从github发送和检索信息。
发布于 2022-03-09 23:11:17
要做的第一件事是将该JSON反序列化为它表示的类结构。
public class GitResponse{
public Node[] PinnedItems {get;set;}
}
public class Node{
public string Name {get;set};
public string Description {get;set;}
....
}等一下,一旦做完这件事,剩下的就很容易了,你只要走那棵树就行了。
反序列化
System.Text.Json.Serailizer.Deserialize<GitResponse>(json);https://stackoverflow.com/questions/71416987
复制相似问题