Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

c# - Skipping parent properly in JsonDeserializer

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...