简体   繁体   English

值不能为空。 反序列化对象Json

[英]Value cannot be null. Deserialize Object Json

I am having issues deserializing this json string to ac# object. 我在将此json字符串反序列化为ac#对象时遇到问题。 I have tried numerous different configuration of the model and i have tried to serialize the code and let the mvc value providers to do this, but i can't get it to work..... So I am sending this JSON string to my controller and then putting it into an object and then creating the correct object to throw it in my database. 我已经尝试了该模型的许多不同配置,并且我尝试序列化代码并让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

This is the string before i send it to my controller: 这是我发送给控制器之前的字符串:

var data = JSON.stringify({
            QuestionTitle: title,
            Keywords: key,
            Description: desc,
            Comments: comments,
            QuestionType: type,
            choices: {
                DisplayText: text,
                OrderNumber: order,
                is_correct:is_correct
            }
        });

This is the controller method: 这是控制器方法:

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");
    }

and this is the model: 这是模型:

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; }
    }

finally, this is the actual string of data that is getting passed: 最后,这是要传递的实际数据字符串:

{"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
  }
} 

Solution Change the JS where data was defined to the following: 解决方案将定义data的JS更改为以下内容:

            var data = {
            "QuestionTitle": title,
            "Keywords": key,
            "Description": desc,
            "Comments": comments,
            "QuestionType": type,
            "choices": {
                "DisplayText": text,
                "OrderNumber": order,
                "is_correct":false
            }
        };

The real solution for your problem is to use MVC's model binding feature . 解决您问题的真正方法是使用MVC的模型绑定功能 Change your method parameter type to your class and MVC will bind the JSON value to it. 将您的方法参数类型更改为您的类,MVC会将JSON值绑定到该类。

public ActionResult Create(SimpleQuestion model)
{
  // use model now
  // TO DO :Save and redirect
}

Make sure you are specifying the contentType property value as " application/json " in your ajax call. 确保在ajax调用中将contentType属性值指定为“ application / json ”。

Also you do not need to call stringify if it is a valid JSOn. 另外,如果它是有效的JSOn,则无需调用stringify。 The below code will work fine 下面的代码可以正常工作

$(function () {
    var data = {
        "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
        }
    };      
    $.post("@Url.Action("Create","Home")", data, null, 'application/json');

});

在此处输入图片说明

Your problem is - as so often when it comes to JSON - a mismatch between the JSON and your data structure. 您的问题是-与JSON一样多-JSON和数据结构之间不匹配。

In your data structure you have this: A list of QuestionChoices. 在您的数据结构中,您将具有:QuestionChoices列表。

public List<QuestionChoices> choices { get; set; }

In your JSON you send this: A single object. 在JSON中,您将发送以下内容: 单个对象。

        choices: {
            DisplayText: text,
            OrderNumber: order,
            is_correct:is_correct
        }

Please keep in mind that in JSON an array (or a list) is described with [] . 请记住,在JSON中,数组[或列表][]描述。 So the correct JSON would be this: 因此正确的JSON是这样的:

        choices: [{
            DisplayText: text,
            OrderNumber: order,
            is_correct:is_correct
        }]

Multiple choices would be seperated within the [] by a comma. 多个选择将在[]中用逗号分隔。

The problem originates in your JavaScript code already, where you define choices to be a single object - not an array containing a single object. 问题出在您的JavaScript代码中,您在其中将choices定义为单个对象-而不是包含单个对象的数组。 Fix that, and your problem should disappear. 解决该问题,您的问题应该消失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM