EDIT:事实证明,我可以很好地反序列化,问题实际上是当我试图循环来获取问题时。尽管"对象引用未设置为对象的实例",但仍出现相同错误。我之所以编辑这篇文章,是因为我无法删除帖子,因为它已经有答案了。
//deserialize json
ResponsesList responses = JsonConvert.DeserializeObject<ResponsesList>(_ResponseContent);
if (responses != null)
{
//loop through responses
foreach (ResponsesList.Data data in responses.data)
foreach (ResponsesList.Questions question in data.questions)
foreach (ResponsesList.Answer answer in question.answers)
{
//upsert each response
UpsertResponse(survey_id, data.respondent_id, question.question_id, answer.row, answer.col);
}
}
这一行是发生错误的地方
foreach (ResponsesList.Questions question in data.questions)
这是我正在反序列化为的类
//get_responses
public class ResponsesList
{
public int status { get; set; }
public List<Data> data { get; set; }
public class Data
{
public string respondent_id { get; set; }
public List<Questions> questions { get; set; }
}
public class Questions
{
public List<Answer> answers { get; set; }
public string question_id { get; set; }
}
public class Answer
{
public string row { get; set; }
public string col { get; set; }
}
}
我刚刚在LINQPad:中成功地反序列化了您的示例字符串
var str =
@"{
""status"": 0,
""data"": [
null,
null
]
}";
JsonConvert.DeserializeObject<ResponsesList>(str).Dump();
这告诉我你的_ResponseContent不是你想象的那样。
想明白了。它只需要进行一些检查,以确保我试图循环通过的对象不是空的。
示例:
//deserialize json
ResponsesList responses = JsonConvert.DeserializeObject<ResponsesList>(_ResponseContent);
if (responses != null)
{
//loop through responses
foreach (ResponsesList.Data data in responses.data)
if (data != null)
{
foreach (ResponsesList.Questions question in data.questions)
if (question != null)
{
foreach (ResponsesList.Answer answer in question.answers)
{
//upsert each response
UpsertResponse(survey_id, data.respondent_id, question.question_id, answer.row, answer.col);
}
}
}
}
不过,我感谢大家的回复。
当我遇到这个错误时,我通过在执行循环之前添加一个null测试来修复我的错误。
我会使用这个网站来创建您的类:http://json2csharp.com/
这就是它吐出的:
public class RootObject
{
public int status { get; set; }
public List<object> data { get; set; }
}