![](/img/trans.png)
[英]System.Text.Json.JsonException: The JSON value could not be converted
[英]System.Text.Json.JsonException: Unable to convert Json to DataModel
我正在嘗試從 json 文件將數據播種到數據庫中,但我一直遇到相同的錯誤。 如下所示的堆棧跟蹤。 我有一個 AppQuestion 類和一個 IncorrectAnswer 類。 數據旨在匹配這些模型並傳遞到我的數據庫中。 嘗試反序列化時,似乎 Seed Incorrect 數組導致了錯誤。 我更喜歡使用 System.Text.Json 而不是 Newsoft。 有沒有辦法處理數據並忠於我的模型。
種子數據.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
AppQuestion
類中的Incorrect
屬性是IncorrectAnswer
對象的集合,但在您的 json 中incorrect
是字符串數組。
您需要更改模型或 json。
最后,我發現一個頁面提到在屬性中明確說明 DataMember。 我認為播種數據應該有一個更清晰的結果,但這目前有效。
public class Example
{
[DataMember(Name="Question")]
public string Question { get; set; }
[DataMember(Name="Incorrect")]
public IList<string> Incorrect { get; set; }
[DataMember(Name="Correct")]
public string Correct { get; set; }
}
public class Seed
{
public 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 myDeserializedClass = JsonSerializer.Deserialize<List<Example>>(questionData);
foreach (var item in myDeserializedClass)
{
var appQuestion = new AppQuestion();
var incorrectAnswerList = new List<IncorrectAnswer>();
appQuestion.Question = item.Question;
appQuestion.Correct = item.Correct;
foreach (var thing in item.Incorrect)
{
var incorrectAnswer = new IncorrectAnswer();
incorrectAnswer.Incorrect = thing;
incorrectAnswerList.Add(incorrectAnswer);
}
appQuestion.Incorrect = incorrectAnswerList;
context.Questions.Add(appQuestion);
}
await context.SaveChangesAsync();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.