【发布时间】:2021-02-09 03:22:04
【问题描述】:
我正在尝试从 json 文件将数据播种到数据库中,但我一直遇到同样的错误。如下所示的堆栈跟踪。我有一个 AppQuestion 类和一个 IncorrectAnswer 类。数据旨在匹配这些模型并传递到我的数据库中。尝试反序列化时,似乎是 Seed Incorrect 数组导致了错误。我更喜欢使用 System.Text.Json 而不是 Newsoft。有没有办法处理数据并忠实于我的模型。
SeedData.json
[
{
"Question": "Question1",
"Incorrect": ["Answer1", "Answer2", "Answer3"],
"Correct": "Answer4"
}, {
"Question": "Question2",
"Incorrect": ["Answer1", "Answer2", "Answer4"],
"Correct": "Answer3"
}
]
C# 代码
public class Seed
{
public static async Task SeedQuestions(DataContext context)
{
if (await context.Questions.AnyAsync()) return;
var questionData = await System.IO.File.ReadAllTextAsync("Data/QuestionSeedData.json");
var questions = JsonSerializer.Deserialize<List<AppQuestion>>(questionData);
foreach(var question in questions)
{
context.Questions.Add(question);
}
await context.SaveChangesAsync();
}
}
public class AppQuestion
{
public int Id { get; set; }
public string Question { get; set; }
public ICollection<IncorrectAnswer> Incorrect { get; set; }
public string Correct { get; set; }
}
public class IncorrectAnswer
{
public int Id { get; set; }
public string Incorrect { get; set; }
public AppQuestion AppQuestion { get; set; }
public int AppQuestionId { get; set; }
}
public class DataContext : DbContext
{
public DataContext( DbContextOptions options) : base(options)
{
}
public DbSet<AppQuestion> Questions {get; set;}
public DbSet<AppUser> Users { get; set; }
}
public class Program
{
public static async Task Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
using var scope = host.Services.CreateScope();
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<DataContext>();
await context.Database.MigrateAsync();
await Seed.SeedQuestions(context);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred during migration");
}
await host.RunAsync();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
堆栈跟踪
fail: API.Program[0]
An error occurred during migration
System.Text.Json.JsonException: The JSON value could not be converted to API.Entities.IncorrectAnswer. Path: $[0].Incorrect[0] | LineNumber: 3 | BytePositionInLine: 28.
at System.Text.Json.ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type propertyType)
at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
at System.Text.Json.Serialization.Converters.IEnumerableDefaultConverter`2.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, TCollection& value)
at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
at System.Text.Json.JsonPropertyInfo`1.ReadJsonAndSetMember(Object obj, ReadStack& state, Utf8JsonReader& reader)
at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
at System.Text.Json.Serialization.Converters.IEnumerableDefaultConverter`2.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, TCollection& value)
at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
at System.Text.Json.JsonSerializer.ReadCore[TValue](JsonConverter jsonConverter, Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
at System.Text.Json.JsonSerializer.ReadCore[TValue](Utf8JsonReader& reader, Type returnType, JsonSerializerOptions options)
at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, Type returnType, JsonSerializerOptions options)
at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options)
at API.Data.Seed.SeedQuestions(DataContext context) in C:\Users\fahua\Documents\TriviaTandem\API\Data\Seed.cs:line 20
at API.Program.Main(String[] args) in C:\Users\fahua\Documents\TriviaTandem\API\Program.cs:line 26
【问题讨论】:
-
不要使用图片,添加代码。
-
已更新。谢谢。
-
为什么
"Question "令牌后面有空格?是有意的吗? -
不,不是有意的,它似乎并没有因此引起问题。编辑它没有空间。问题仍然存在。
标签: c# json serialization seed system.text.json