gpt4 book ai didi

c# - 反序列化List Json C#中的List

转载 作者:行者123 更新时间:2023-11-30 20:17:12 26 4
gpt4 key购买 nike

我有 JSON 格式的问题列表。他们每个人都包含答案列表。当我反序列化它时,答案列表不会反序列化。我只是收到空答案列表的问题。我该如何解决这个问题?

我的反序列化

List<QuestionTxt> myDeserializedObjList = (List<QuestionTxt>)Newtonsoft.Json.JsonConvert.DeserializeObject(File.ReadAllText(@"d:\test.txt"), typeof(List<QuestionTxt>));

JSON

[
{
"answers": [
{
"answer": "1",
"text": "First"
},
{
"answer": "Second",
"text": "2"
}
],
"cost": 1.0,
"count": 2,
"image": false,
"imagePath": null,
"name": "Numbers",
"about": "Numbers",
"solve": false,
"type": "Сonformity",
"Id": "cnf0"
},
{
"answers": [
{
"answer": "+",
"text": "One"
},
{
"answer": "-",
"text": "Two"
}
],
"cost": 1.0,
"count": 2,
"image": false,
"imagePath": null,
"name": "Numbers 2",
"about": "Numbers 2",
"solve": false,
"type": "One",
"Id": "rdb0"
}
]

问题文本

Answer class

回答

class Answer
{
private string text_;
private string answer_;

public Answer(string text, string answer)
{
this.text = text;
this.answer = answer;
}

public string answer { get => answer_; set => answer_ = value; }
public string text { get => text_; set => text_ = value; }
}

最佳答案

属性QuestionTxt.answers 应该是public(你有internal)

public class QuestionTxt
{
public List<Answer> answers { get; set; } // notice public!
public string name { get; set; }

public QuestionTxt()
{
answers = new List<Answer>();
}
}

或者,如果您希望将其保留在内部 - 使用JsonPropertyAttribute

public class QuestionTxt
{
[JsonProperty()]
internal List<Answer> answers { get; set; } // notice internal!
public string name { get; set; }

public Question()
{
answers = new List<Answer>();
}
}

当然,所有你想要反序列化的类都应该有无参数的构造函数。

作为 JsonPropertyAttribute 的通知,您可以自由地遵循 .Net 属性名称约定,而不会违反 json 约定

public class QuestionTxt
{
[JsonProperty("answers")]
public List<Answer> Answers { get; set; }

[JsonProperty("name")]
public string Name{ get; set; }

public Question()
{
Answers = new List<Answer>();
}
}

public class Answer
{
[JsonProperty("answer")]
public string Value { get; set; }

[JsonProperty("text")]
public string Text { get; set; }
}

关于c# - 反序列化List Json C#中的List,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45944644/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com