2012-11-08 3 views
8

특정 클래스의 객체에 대해 JsonResult를 반환하는 동작이 있습니다. null 필드를 피하기 위해이 클래스의 속성을 일부 특성을 사용하여 장식했습니다.MVC4 null없이 JsonResult를 반환하는 동작

private class GanttEvent 
    { 
     public String name { get; set; } 

     [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] 
     public String desc { get; set; } 

     [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] 
     public List<GanttValue> values { get; set; } 
    } 

그리고 내 행동에 나는 내가 사용 돌려주는 객체

var res = new List<GanttEvent>(); 

사용 : 클래스 정의는 Unfortunatelly

return Json(res, JsonRequestBehavior.AllowGet); 

, 난 여전히 출력에서 ​​null 값을 수신하고 있습니다에게 :

[{"name":"1.1 PREVIOS AL INICIO ","desc":null,"values":null},{"name":"F04-PGA-S10","desc":"Acta preconstrucción","values":null},{"name":"F37-PGA-S10","desc":"Plan de inversión del anticipo","values":null},{"name":"F09-PGA-S10","desc":"Acta de vecindad","values":null},{"name":"F05-PGA-S10","desc":"Acta de inicio","values":null},{"name":"F01-PGA-S10","desc":"Desembolso de anticipo","values":null}] 

am I 뭔가를 놓치고 있거나 뭔가 잘못하고있는 것?

답변

6

Brad Christie가 말한 것처럼 MVC4 스틸은 JavaScriptSerializer를 사용하므로 객체를 Json.Net에서 직렬화하려면 여러 단계를 수행해야합니다.

먼저, 다음과 같이 (this solution 기준) JsonResult에서 새 클래스 JsonNetResult 상속 :

protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior) 
{ 
    return new JsonNetResult(data, contentType, contentEncoding, behavior); 
} 
+0

이 답변이 아직 관련이 있는지는 모르겠지만 이와 같은 것이 필요하고 코드의 C/P를 수행했습니다. 불행히도 예상대로 작동하지 않지만 JsonNetResult 클래스를 약간 편집했습니다. var serializedObject = JsonConvert.SerializeObject (Data, Formatting.None, new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore}); ... 이제 완벽하게 작동합니다. 감사! – robertpaulsen

0

내 제안은 하나의 GanttEvent 객체를 JSON으로 직렬화하면 어떻게 될지보고 싶습니다. 또한 Json에게 전화가 왔는지 확인하십시오.

1

Controller.JsonJsonPropertyAttribute의 출처가되는 Newtonsoft Json library이 아닌 JavaScriptSerializer을 사용합니다.

Newtonsoft 라이브러리 라이브러리를 사용하여 그런 식으로 직렬화 된 결과를 반환하거나 Json을 계속 호출하고 null을 무시하는 converter을 작성해야합니다.

+0

:

public class JsonNetResult : JsonResult { public JsonNetResult() { this.ContentType = "application/json"; } public JsonNetResult(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior jsonRequestBehavior) { this.ContentEncoding = contentEncoding; this.ContentType = !string.IsNullOrWhiteSpace(contentType) ? contentType : "application/json"; this.Data = data; this.JsonRequestBehavior = jsonRequestBehavior; } public override void ExecuteResult(ControllerContext context) { if (context == null) throw new ArgumentNullException("context"); var response = context.HttpContext.Response; response.ContentType = !String.IsNullOrEmpty(ContentType) ? ContentType : "application/json"; if (ContentEncoding != null) response.ContentEncoding = ContentEncoding; if (Data == null) return; // If you need special handling, you can call another form of SerializeObject below var serializedObject = JsonConvert.SerializeObject(Data, Formatting.None); response.Write(serializedObject); } } 

그런 다음 컨트롤러에 새 클래스를 사용하는 JSON 메소드를 오버라이드 (override)를 고마워, 나는 그것에 대해 의심 스러웠다. 그리고 너는 내 생각을 확인했다. 결국, Json.Net은 기본 시리얼 라이저이지만 ** MVAP 웹 사이트가 아닌 ** WebAPI **에서만 사용할 수 있습니다. – Farlop

관련 문제