我在将此 json 字符串反序列化为 ac# 对象时遇到问题。我尝试了许多不同的模型配置,我尝试序列化代码并让 mvc 值提供程序执行此操作,但我无法让它工作.....所以我将此 JSON 字符串发送到我的控制器,然后将其放入对象中,然后创建正确的对象以将其放入我的数据库中。
[ArgumentNullException: Value cannot be null.
Parameter name: value]
Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings) +162
Newtonsoft.Json.JsonConvert.DeserializeObject(String value, JsonSerializerSettings settings) +66
InSight.Controllers.QuestionController.CreateSimpleQuestion(String json) +25
这是我将它发送到我的控制器之前的字符串:
var data = JSON.stringify({
QuestionTitle: title,
Keywords: key,
Description: desc,
Comments: comments,
QuestionType: type,
choices: {
DisplayText: text,
OrderNumber: order,
is_correct:is_correct
}
});
这是控制器方法:
public ActionResult CreateSimpleQuestion(string json)
{
SimpleQuestion temp = JsonConvert.DeserializeObject<SimpleQuestion>(json);
Question question = new Question();
question.QuestionTitle = temp.QuestionTitle;
question.QuestionType = temp.QuestionType;
question.Keywords = temp.Keywords;
question.is_counted = true;
question.DateCreated = DateTime.Now;
question.Comments = temp.Comments;
question.QuestionType = "Simple";
db.Questions.Add(question);
db.QuestionChoices.Add(temp.choices.First());
db.SaveChanges();
return RedirectToAction("Index");
}
这是模型:
public class SimpleQuestion
{
public int QuestionId { get; set; }
public string QuestionTitle { get; set; }
public DateTime DateCreated { get; set; }
public string QuestionType { get; set; }
public string Keywords { get; set; }
public bool is_counted { get; set; }
public string Description { get; set; }
public string Comments { get; set; }
public List<QuestionChoices> choices { get; set; }
}
最后,这是正在传递的实际数据字符串:
{"QuestionTitle":"This is the Question Title",
"Keywords":"Blue pony, sharks",
"Description":"This is the description field.",
"Comments":"No comment has been left.",
"choices":{
"DisplayText":"Will it rain tomorrow?",
"OrderNumber":"1","is_correct":false
}
}
解决方案将定义
的JS更改data
为以下内容:
var data = {
"QuestionTitle": title,
"Keywords": key,
"Description": desc,
"Comments": comments,
"QuestionType": type,
"choices": {
"DisplayText": text,
"OrderNumber": order,
"is_correct":false
}
};