Here is my JSON string:
[
{
"Order": 1,
"IssueId": 83719,
"Journal": "HLRF",
"Identity": "HLRF, Vol.137, Iss.4, y.2024, February 2024",
"Web": "https://harvardlawreview.org/forum/issue/83719",
"Articles": [
{
"Link": "https://harvardlawreview.org/forum/article/1451533",
"Pdf": 3789188
},
{
"Link": "https://harvardlawreview.org/forum/article/1451561",
"Pdf": 3789306
},
{
"Link": "https://harvardlawreview.org/forum/article/1451574",
"Pdf": 3789358
}
]
}
]
And I am using Json.Net and object structure like this:
var issues = JsonConvert.DeserializeObject<List<Issue>>("___Json.String___");
public class Issue
{
public int Order { get; set; }
public int IssueId { get; set; }
public string Journal { get; set; }
public string Identity { get; set; }
public string Web { get; set; }
public List<Article> Articles { get; set; }
}
public class Article
{
public string Link { get; set; }
public int Pdf { get; set; }
}
From the JSON, I know the Pdf
number like 3789306
. It is located in the first issue and the second article.
So I want to get the parent issue’s id: IssueId
. In our example 83719
. But I did not manage it.
2
Answers
As you deserialize into
List<Issue>
, this will be easier to achieve via System.Linq to search the parent that contains the children withPdf
is 3789306.For the handling in case that
articleId
may not exist, use.FirstOrDefault()
and null-conditional operator(?.
).This can be achieved by using Linq query. First of all you need to flattens the structure using
SelectMany
to access all articles across issues. Then, need to filters for the article with the matching Pdf and selects the IssueId from its parent.Finally, it retrieves the first matching element or indicates if no article was found.
Full Demo:
Output:
Note: For more linq techniques, pleaes refer to this official document.