我有一个 JSON 对象,其中包含两个空数组:“subQuestions” 和 “answers”。我已经为该对象创建了相应的类,但在处理这些空数组时遇到了困难。以下是我目前的代码:
JSON 示例
{
"questions": [
{
"questionId": "1",
"question": "Ipsum",
"helpText": null,
"questionType": "MultipleChoice",
"answerChoices": [
{
"answerChoiceId": "b2b-2.01-answer1",
"value": "Lorem",
"subQuestions": []
}
],
"answers": []
}
]
}
类定义
public class AnswerChoice
{
public string answerChoiceId { get; set; }
public string value { get; set; }
public List subQuestions { get; set; }
}
public class Question
{
public string questionId { get; set; }
public string question { get; set; }
public object helpText { get; set; }
public string questionType { get; set; }
public List answerChoices { get; set; }
public List answers { get; set; }
}
public class ObjectRoot
{
public string productId { get; set; }
public List questions { get; set; }
}
构建 JSON 对象
var jsOnBody= new ObjectRoot()
{
productId = productId,
questiOns= new[]
{
new Question()
{
questiOnId= "b2b-2.01",
question = "Vad är syftet med ert engagemang hos oss?",
helpText = null,
questiOnType= "MultiChoise",
answerChoices = new[]
{
new AnswerChoice
{
answerChoiceId = "",
value = "",
subQuestiOns= new List() // 初始化为空集合
}
}.ToList(),
answers = new List()
}
}.ToList()
};
关键在于确保所有集合类型(如 List
)在初始化时正确处理空集合。对于空数组,可以使用 List()
构造函数来初始化。这样可以避免潜在的错误,并确保 JSON 序列化和反序列化过程顺利进行。