无法将 JSON 反序列化为列表?

问题描述 投票:0回答:2

我正在开发一个机器人,该机器人将从存储在 JSON 中的琐事问题列表中提取数据,但它似乎无法将 JSON 识别为列表,即使我认为我已经正确地说出了它。

相关代码: C#:

class Question
{
    public string Catagory { get; set; }
    public string QuestionText { get; set; }
    public string Answer { get; set; }
    public int Points { get; set; }
    public bool asked { get; set; }
}

class TriviaGame
{
    public List<Question> QuestionList = new List<Question>();

    public TriviaGame()
    {
        QuestionList = JsonConvert.DeserializeObject<List<Question>>(File.ReadAllText(@"filepath"));
    }

JSON:

{
    "Question" : [
    {
        "Catagory": "text",
        "QuestionText": "text",
        "Answer": "text",
        "Points": integer,
        "Asked": false
    },
    {
        "Catagory": "text",
        "QuestionText": "text",
        "Answer": "text",
        "Points": integer,
        "Asked": false
    },
    {
        "Catagory": "text",
        "QuestionText": "text",
        "Answer": "text",
        "Points": integer,
        "Asked": false
    }]
}

用占位符文本替换了 JSON 文件中的文本,但值不是它验证的问题。 出于隐私原因,将实际文件路径替换为单词文件路径,但文件路径有效,因为它在引发错误之前确实提取了文件。

给出的错误:

Newtonsoft.Json.JsonSerializationException:'无法反序列化 当前 JSON 对象(例如 {"name":"value"})转换为类型 'System.Collections.Generic.List`1[TriviaBot.Question]' 因为 type 需要一个 JSON 数组(例如 [1,2,3])才能正确反序列化。到 修复此错误,或者将 JSON 更改为 JSON 数组(例如 [1,2,3]) 或者更改反序列化类型,使其成为普通的 .NET 类型(例如 不是像整数这样的原始类型,也不是像数组这样的集合类型 或列表),可以从 JSON 对象反序列化。 还可以将 JsonObjectAttribute 添加到类型中以强制其 从 JSON 对象反序列化。路径“问题”,第 2 行,位置 13。'

c# json serialization deserialization
2个回答
0
投票

您拥有的 json 结构有一个名为 Question 的属性,该属性包含一个项目数组,而不是一个问题数组。正如另一个答案所述,您可以修改 json 文件并删除 Question 属性。或者,如果您无法修改该结构(例如,如果您从不属于您的服务中获取它),则可以按如下方式修改类定义:

class Items
{
    public List<Item> Question {get;set;}
} 
class Item
{
    public string Catagory { get; set; }
    public string QuestionText { get; set; }
    public string Answer { get; set; }
    public int Points { get; set; }
    public bool asked { get; set; }
}

然后加载对象。

public List<Item> QuestionList = new List<Item>();

public TriviaGame()
{
    var deserialized = JsonConvert.DeserializeObject<Items>(File.ReadAllText(@"filepath"));
    QuestionList = deserialized.Question;
}

0
投票

问题出在JSON文件中;它描述的是一个映射而不是一个数组。 尝试删除

{
"Question" :

开头并删除末尾的

}

© www.soinside.com 2019 - 2024. All rights reserved.