2012-02-24 4 views
0

아래 이미지에서와 같이 데이터를 반환 할 MVC 작업 메서드가 있습니다.Json 데이터 읽기

동작 방법

[HttpPost] 
public JsonResult LegalCheck(string jsonPackage) 
{ 
    var serializer = new JavaScriptSerializer(); 
    var comments = serializer.Deserialize<Dictionary<string, string>>(jsonPackage.Substring(jsonPackage.IndexOf('{'), jsonPackage.LastIndexOf('}'))); 
    var results = MyService.GetViolations(comments, CookieManager.ClientId); 
    return Json(results); 
} 

enter image description here

결과는 아래의 데이터를 필요 이드의 (CommentTextarea-1181_1183 등) 및 텍스트 영역을 보유하고있다. 결과를 어떻게 철저히 조사 할 수 있습니까? results.length, results [0]이 (가) 정의되지 않은 것으로 표시됩니다. 이 Json 데이터를 반복 할 수 있습니까? 아니면 반환되는 json 데이터를 변경해야합니까?

results 
Count = 2 
    [0]: {[CommentTextarea_1181_1183, Mynamespace.Services.Legal[]]} 
    [1]: {[CommentTextarea_1181_1184, Mynamespace.Services.Legal[]]} 

가]}

[Serializable] 
    public class Legal 
    { 
     public string Phrase { get; set; } 
     public int StartIndex { get; set; } 
    } 

감사 아래와 같이 법률 아이오와 클래스는

+0

당신이 JSON 그렇게 보이는 돌아오고 무엇을 게시 할 수 있습니까? – spinon

+0

결과 (위 이미지)는 돌아 오는 json입니다. 액션 메소드에 내장 된 데이터를 게시 하시겠습니까? – San

+0

그래, 그저 그 이미지에서 보이는 것과 같은 것을 만들 수 없다. 또한 그것이 어떻게 구조화되어 있는지보기를 기대하고있었습니다. 리터럴 JSON 문자열과 같습니다. – spinon

답변

0

그것은 그 MyService.GetViolations 메소드가 리턴 보인다 아래로

데이터는 그 액션 메소드는 int로 a Dictionary<string, Legal[]>. ASP.NET MVC 3에서 JSON 응답을 serialize하기 위해 사용하는 JavaScriptSerializer은 사전을 serialize 할 때 javascript 배열을 생성하지 않습니다. 자바 스크립트 객체를 생성합니다. 따라서이 객체의 인덱스가 0 기반 정수가 아니기 때문에 반복 할 수 없습니다.

그래서 당신이 개체에 대해 정의 된 모든 속성을 열거 할 수 루프 순서 :

$.ajax({ 
    url: '@Url.Action("LegalCheck")', 
    type: 'POST', 
    success: function (result) { 
     for (var prop in result) { 
      if (result.hasOwnProperty(prop)) { 
       // prop is the key and result[prop] is the legals array 
       var legals = result[prop]; 

       alert('the key is ' + prop + ' and the value is ' + legals[0].Phrase); 
      } 
     } 
    } 
});