Home > Back-end >  How to deserialize a child element of a JSON object to a property in the parent model using System.T
How to deserialize a child element of a JSON object to a property in the parent model using System.T

Time:07-14

First off, I had a hard time with the title of this one; I'll edit it if I get any better suggestions.

I have a json string that looks like this

{
   "chapters": [
      {
         "id": 0,
         "tags": {
            "title": "Chapter 1"
         }
      },
      {
         "id": 1,
         "tags": {
            "title": "Chapter 2"
         }
      }
   ]
}

My model for this is as such

public class Chapter
{
   [JsonPropertyName("id")]
   public int Id { get; set; }

   [JsonPropertyName("tags")]
   public ChapterTags Tags { get; set; }

   [JsonIgnore]
   public string Title
   {
      get { return Tags.Title; }
      set { if (Tags.Title != value) Tags.Title = value; }
   }
}
 
public class ChapterTags
{
   [JsonPropertyName("title")]
   public string Title { get; set; }
}

and here is the code I'm using to deserialize the json

var jsonTask = GetJsonAsync();

using var jsonResults = JsonDocument.Parse(await jsonTask);

var jsonChapters = jsonResults.RootElement.GetProperty("chapters");

List<Chapter> chapters = JsonSerializer.Deserialize<List<Chapter>>(jsonChapters) ?? new();

I want to get rid of the Tags property and the ChapterTags class and just be left with

public class Chapter
{
   [JsonPropertyName("id")]
   public int Id { get; set; }

   public string Title {get; set;}
}

as a simple single class model.

My only thought was to use a JsonConverter but could not figure out how to make that work. I can't change the format of the json input because it is being generated by an outside source.

Also, if it matters, I will never have to re-serialize the object back to json.

I am using VS2022 Preview, as that is currently the only way to work with .Net Maui.

CodePudding user response:

I believe this question should help you Custom Deserialization using Json.NET

You are right JsonConverter is something needed here.

CodePudding user response:

try this

List<Chapter> chapters =   JsonDocument.Parse(json)
                           .RootElement.GetProperty("chapters")
                           .EnumerateArray()
                           .Select(c => new Chapter
                           {
                               Id = Convert.ToInt32(c.GetProperty("id").ToString()),
                               Title = c.GetProperty("tags").GetProperty("title").ToString()
                           })
                           .ToList();
  • Related