Home Full Site
ASP.NET MVC 에서의 JSON

ASP.NET MVC는 Controller 클래스에 기본적으로 JSON을 리턴하는 메서드를 지원하고 있다. 즉, Controller.Json() 메서드를 사용하면 .NET 객체를 JSON으로 변환하여 JsonResult 클래스 객체에 넣게 된다. JsonResult는 ActionResult의 파생클래스이므로 이 객체를 리턴하면 JSON이 직접 리턴된다.

ASP.NET MVC는 디폴트 JSON Serializer로서 내부적으로 JavaScriptSerializer을 사용하고 있다.

아래는 (1) MVC 컨트롤러에서 .NET 객체를 JSON으로 변형하여 리턴하는 예제와 (2) 클라이언트에서 jQuery Ajax를 사용하여 서버 API를 호출하는 예제이다.


예제

// MVC 서버 컨트롤러 예제
public class PersonController : Controller
{
    [HttpGet]
    public ActionResult GetPerson(int id)
    {
        Person pObj = new Person { Id = id, Name = "Lee" };
        return Json(pObj, JsonRequestBehavior.AllowGet);
    }
    
    //...
}

class Person
{
    public int Id { get; set; }
    public string Name { get; set; }        
}

// 클라이언트에서 AJAX로 MVC를 호출하는 예제

<script type="text/javascript">
    function getData() {
        $.ajax({
            url: '/Person/GetPerson',
            type: 'GET',
            data: { 'id': '1' },
            success: function (data) {
                console.log(data);
                alert(data.Id);
                alert(data.Name);
            },
            error: function (xhr) {
                alert(xhr);
            }
        });
    }
</script>
<input type="button" value="Get Data" onclick="getData()" />



익명 타입을 이용한 간단한 JSON

ASP.NET MVC에서 Controller.Json() 메서드를 사용하여 간단한 JSON을 리턴하고자 할 때 익명 타입((Anonymous Type)을 이용하면 별도의 타입/클래스를 매번 만들지 않아도 되는 잇점이 있다. 아래는 간단한 속성들을 갖는 익명타입으로 만들어 이를 JSON으로 리턴하는 예제이다.

예제

// 익명 타입(Anonymous Type)을 이용한
// 간단한 JSON 예제

public class PersonController : Controller
{
    [HttpGet]
    public ActionResult GetPerson()
    {        
        return Json(new { Id = 1, Name = "Lee" }, JsonRequestBehavior.AllowGet);
    }    
}



© csharpstudy.com