Search code examples
c#jsonjson.netdotnet-httpclientjson-deserialization

Deserialize JSON with nested lists from HttpResponseMessage


I've already tried some solutions described on Stackoverflow (e.g. Best way to deserialize a nested list in a json - C#).

I have already tried this, but it doesn't work for me. Maybe I have made a mistake somewhere.

This is my code to do an HTTP request:

HttpClient httpClient = new HttpClient();

HttpResponseMessage response = await httpClient.PostAsync(url, someData);

response.EnsureSuccessStatusCode();

string responseString = response.Content.ReadAsStringAsync().Result;

AllChapters allChapters = JsonConvert.DeserializeObject<AllChapters>(responseString);

But when I run my code, allChapters is always empty (null) even if there is data inside responseString. Do any of you have a solution for this? I might have missed something, but I don't know what exactly.

And this is what my responseString looks like:

{
  "AllChapters": [
    {
      "ChapterIndex": 1,
      "ChapterParagraphs": [
        {
          "ParagraphIndex": 1,
          "Text": "SomeText"
        }
      ],
      "Title": "First Chapter"
    },
    {
      "ChapterIndex": 2,
      "ChapterParagraphs": [
        {
          "ParagraphIndex": 1,
          "Text": "SomeText"
        },
        {
          "ParagraphIndex": 2,
          "Text": "SomeText"
        }
      ],
      "Title": "Second Chapter"
    }
  ]
}

I've created three classes to store the data:

AllChapters

public class AllChapters
{
    public List<OneChapter> OneChapter { get; set; }
}

OneChapter

public class OneChapter
{
    public int ChapterIndex { get; set; }

    public List<ChapterParagraph> ChapterParagraphs { get; set; }

    public string Title { get; set; }

    public OneChapter()
    {
        ChapterIndex = 0;
        ChapterParagraphs = new List<ChapterParagraph>;
        Title = string.empty;
    }
}

ChapterParagraph

public class ChapterParagraph
{
    public int ParagraphIndex { get; set; }

    public string Text { get; set; }

    public ParagraphScore()
    {
        ParagraphIndex = 0;
        Text = string.Empty;
    }
}

Solution

  • Your JSON response doesn't match with your AllChapters class. In your root class, it consists of the AllChapters property:

    With JsonPropertyName attribute as corrected by @Ibram,

    public class AllChapters
    {
        [JsonPropertyName("AllChapters")]
        public List<OneChapter> Chapters { get; set; }
    }
    

    or renaming the root class:

    public class ReadingMaterial
    {
        public List<OneChapter> AllChapters { get; set; }
    }
    
    ReadingMaterial readingMaterial = JsonConvert.DeserializeObject<ReadingMaterial>(responseString);