微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

System.Text.Json.JsonException:无法将Json转换为DataModel

如何解决System.Text.Json.JsonException:无法将Json转换为DataModel

我正在尝试将数据从json文件播种到数据库中,但是我一直遇到相同的错误。如下所示在堆栈跟踪中。我有一个AppQuestion类和一个IncorrectAnswer类。数据旨在匹配这些模型并传递到我的数据库中。尝试反序列化时,似乎种子不正确数组导致了错误。我宁愿使用System.Text.Json而不是Newsoft。有没有一种方法可以处理数据并忠实于我的模型。

SeedData.json:

[
{
  "Question": "Question1","Incorrect": ["Answer1","Answer2","Answer3"],"Correct": "Answer4"
},{
  "Question": "Question2","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,T& value)
     at System.Text.Json.Serialization.Converters.IEnumerableDefaultConverter`2.OnTryRead(Utf8JsonReader& reader,TCollection& value)
     at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader,T& value)
     at System.Text.Json.JsonPropertyInfo`1.ReadJsonAndSetMember(Object obj,Utf8JsonReader& reader)
     at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryRead(Utf8JsonReader& reader,T& value)
     at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader,ReadStack& state)
     at System.Text.Json.JsonSerializer.ReadCore[TValue](JsonConverter jsonConverter,Utf8JsonReader& reader,ReadStack& state)
     at System.Text.Json.JsonSerializer.ReadCore[TValue](Utf8JsonReader& reader,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

解决方法

Incorrect类中的

AppQuestion属性是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();
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。