我有問題反序列化這個JSON字符串到C#對象。我已經嘗試了許多不同的模型配置,我試圖序列化代碼,並讓mvc值提供程序來做到這一點,但我無法得到它的工作.....所以我發送這個JSON字符串給我控制器,然後將其放入一個對象,然後創建正確的對象將其放入我的數據庫中。值不能爲空。反序列化對象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
}
}
解決方案 變化,其中data
被定義爲以下的JS:
var data = {
"QuestionTitle": title,
"Keywords": key,
"Description": desc,
"Comments": comments,
"QuestionType": type,
"choices": {
"DisplayText": text,
"OrderNumber": order,
"is_correct":false
}
};
在這個JSON'選擇'是一個**單個對象**,而在你的C#對象中它是**對象列表**。在JSON中的對象列表將是:''選擇「:[{obj1},{obj2}]' – user2674389
如何修復stringify函數以顯示?我認爲這是模型活頁夾不能正常工作的實際問題。 – schumacherj
請參閱我的回答。你的JavaScript已經是錯誤的,其中的選擇也是單個對象(而不是陣列) – user2674389