Skipping parent properly in JsonDeserializer

Viewed 140

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?

1 Answers
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace StackOverflow
{
    public class Album
    {
    }

    public class Item
    {
        [JsonPropertyName("album")]
        public Album Album { get; set; }
        [JsonPropertyName("name")]
        public string Name { get; set; }
    }

    public class Tracks
    {
        [JsonPropertyName("href")]
        public string Href { get; set; }
        [JsonPropertyName("items")]
        public List<Item> Items { get; set; }
    }

    public class Root
    {
        [JsonPropertyName("tracks")]
        public Tracks Tracks { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var jsonStr = "{\"tracks\":{\"href\":\"{href_here}\", \"items\" : [{\"album\" : { }, \"name\": \"{name here}\"}]}}";

            var root = JsonSerializer.Deserialize<Root>(jsonStr);

           //Here is your "IEnumerable<Track>"
            var items = root.Tracks.Items;
        }
    }
}

Your model must have such a structure, then it deserialize your data as expected. Then you can use Linq to bring the result to every format you want.

Related