[英]Deserialize JSON in C# EF Core with dummy object for list of string
I am currently attempting to build an ASP.NET Core API.我目前正在尝试构建一个 ASP.NET Core API。
On startup it checks if there is anything in its EF Core powered DB.在启动时,它会检查其 EF Core 驱动的数据库中是否有任何内容。 If not it reads a few JSON files and fills it up.
如果不是,它会读取一些 JSON 文件并将其填满。 To do that it needs to Deserialize them.
为此,它需要反序列化它们。 One of the properties is a List of strings and EF Core doesn't like that.
其中一个属性是字符串列表,而 EF Core 不喜欢这样。 To get around it I made a dummy Model.
为了解决这个问题,我做了一个虚拟的 Model。
public class StringModel
{
public int id { get; set; }
public string str { get; set; }
}
And the other Model.和另一个 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 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'.
Newtonsoft.Json.JsonSerializationException:“将值“a”转换为类型“Project.Models.Primitives.StringModel”时出错。 Path '[0].chapters[0]'
路径 '[0].chapters[0]'
Any ideas?有任何想法吗?
for your json you need this class对于您的 json,您需要这个 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如果你想使用 StringModel 而不是字符串,你的 json 应该是
[
{"id":5,"chapters":[{"id":1,"str":"a"},{"id":2,"str":"b"}]},
{"id":6,"chapters":[{"id":3,"str":"bar"},{"id":4,"str":"foo"}]}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.