'Deserialize JSON in C# EF Core with dummy object for list of string

I am currently attempting to build an ASP.NET Core API.

On startup it checks if there is anything in its EF Core powered DB. If not it reads a few JSON files and fills it up. To do that it needs to Deserialize them. One of the properties is a List of strings and EF Core doesn't like that. To get around it I made a dummy Model.

public class StringModel
{
    public int id { get; set; }
    public string str { get; set; }
}

And the other Model.

public class Book
{
    public int id { get; set; }
    public virtual List<StringModel> chapters { get; set; }
}

This is not how my models look. This is a minimum reproducible example.

JSON

[{
  chapters: ["a","b"]
}, {
  chapters: ["foo","bar"]
}]

And this is where it throws

string json = GetJSONFromFile();
var objs = JsonConvert.DeserializeObject<List<Book>>(json);

Newtonsoft.Json.JsonSerializationException: 'Error converting value "a" to type 'Project.Models.Primitives.StringModel'. Path '[0].chapters[0]'

Any ideas?



Solution 1:[1]

for your json you need this class

     public class Book
    {
        public int id { get; set; }
        public List<string> chapters { get; set; }
    }

and after this you can use

var objs = JsonConvert.DeserializeObject<List<Book>>(json);

if you want to use StringModel instead of string , your json should be

[
{"id":5,"chapters":[{"id":1,"str":"a"},{"id":2,"str":"b"}]},
{"id":6,"chapters":[{"id":3,"str":"bar"},{"id":4,"str":"foo"}]}
]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1