2013-10-31 1 views
0

이 json 문자열을 C# 객체로 비 직렬화하는 데 문제가 있습니다. 모델의 수많은 다른 구성을 시도하고 코드를 serialize하고 mvc 값 공급자가이 작업을 수행 할 수 있지만 작동하도록 가져올 수 없다 ..... 그래서이 JSON 문자열을 보내고 내 컨트롤러로 가져 와서 개체에 넣은 다음 올바른 개체를 만들어 내 데이터베이스에 던져 넣으십시오.값은 null 일 수 없습니다. 객체 역 직렬화

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

내가 내 컨트롤러에 보내기 전에 문자열

마지막으로 이것은 실제 문자열입니다.

{"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 
      } 
     }; 
+1

이 JSON'choices'는 ** 단일 객체 **입니다. 반면 C# 객체에서는 ** 객체 목록 **입니다. JSON의 객체 목록은 다음과 같습니다.''choices ": [{obj1}, {obj2}]' – user2674389

+0

문자열 화 함수를 수정하면 어떻게 되나요? 나는 이것이 모델 바인더가 올바르게 작동하지 않는 이유에 대한 실제적인 문제라고 생각합니다. – schumacherj

+1

내 대답을 참조하십시오. 귀하의 JavaScript가 이미 잘못되었습니다. 선택 항목이 하나의 객체이기도합니다 (배열 대신) – user2674389

답변

3

문제에 대한 진정한 해결책은 MVC의 모델 바인딩 기능을 사용하는 것입니다 건네지고 데이터의. 메서드 매개 변수 유형을 클래스로 변경하면 MVC가 JSON 값을 JSON 값에 바인딩합니다.

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

당신이 당신의 아약스 통화에서 "응용 프로그램/JSON"로 contentType 속성 값을 지정하고 있는지 확인하십시오.

또한 유효한 JSOn 인 경우 stringify를 호출 할 필요가 없습니다. 아래의 코드는 작동 잘

$(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'); 

}); 

enter image description here

+0

모델 바인딩에 많은 문제가있었습니다. 나는 그것을 다시 시도 할 것이다. 코드가 훨씬 깨끗해 보입니다. – schumacherj

+0

초기화 선택 오류 :'... choices '는'속성 '이지만'type '처럼 사용됩니다. – schumacherj

+0

은 속성 이름> – Shyju

2

귀하의 문제는 - 그것은 JSON에 오면 너무 자주 경우 - JSON 및 데이터 구조 사이에 일치하지 않습니다.

데이터 구조에는 다음이 있습니다. QuestionChoices 목록. 당신의 JSON에서

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

이를 보내, • 단일 개체를.

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

JSON로 배열 (또는 목록) [] 설명되어 있음을 유의 해주세요. 올바른 JSON은 다음과 같습니다.

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

여러 선택 사항은 쉼표로 구분됩니다.

choices을 단일 객체로 정의한 JavaScript 코드에서 이미 문제가 발생합니다. 단일 객체를 포함하는 배열이 아닙니다.문제를 해결하면 문제가 사라집니다.

관련 문제