I am receiving an HttpResponseMessage that looks like this (data redacted):
{ "tracks" : { "href" : "{href_here}", "items" : [ { "album" : { //stuff here }, "name": "{name here}" }, { "album" : { //more stuff here }, "name": "{other name here}" } } } My model looks like this:
using System.Text.Json.Serialization; namespace ProjectName.Models { public class Track { [JsonPropertyName("album")] public Album Album { get; set; } [JsonPropertyName("name")] public string Name { get; set; } } } I am then attempting to deserialise the response like so:
var response = await _httpClient.GetAsync("URL HERE"); response.EnsureSuccessStatusCode(); return JsonSerializer.Deserialize<IEnumerable<Track>>(await response.Content.ReadAsStringAsync()); I would like to retrieve a list of Tracks (which corresponds to items in JSON).
I cannot find a way online to "skip" parent properties and only deserialize a specific child (in this case items). I do not need href (and the other properties that I have removed).
Is there a way to do this?
JsonDocumentand query it -- butJsonDocumentdoesn't support JSONPath so there's a little work involved. Most effort would be to write code to manually stream through the JSON tokens until you get what you want usingUtf8JsonReader. More trouble that it's worth really.rootObject.Tracks.Items. The parser will have to read the JSON anyway. See also stackoverflow.com/questions/34222588/…(await JsonSerializerExtensions.DeserializeAnonymousTypeAsync(await response.Content.ReadAsStreamAsync(), new { tracks = new { items = default(IEnumerable<Track>) } }))?.tracks?.items;