반응형

There are quite a bit of answers to handle it client side, but you can change the output server side if you desired.

There are a few ways to approach this, I'll start with the basics. You'll have to subclass the JsonResult class and override the ExecuteResult method. From there you can take a few different approaches to change the serialization.

Approach 1: The default implementation uses the . If you take a look at the documentation, you can use the RegisterConverters method to add custom . There are a few problems with this though: The JavaScriptConverter serializes to a dictionary, that is it takes an object and serializes to a Json dictionary. In order to make the object serialize to a string it requires a bit of hackery, see . This particular hack will also escape the string.

 

번역:

클라이언트측에서 처리할 수 있는 답변이 꽤 많지만, 원한다면 출력 서버측을 변경할 수 있다.
여기에 접근하는 방법에는 몇 가지가 있는데, 기본부터 짚어보겠다. JsonResult 클래스를 하위 클래스로 분류하고 ExecuteResult 메소드를 재정의하십시오. 거기서 당신은 연재물을 바꾸기 위해 몇 가지 다른 접근법을 취할 수 있다.
접근 1:
기본 구현은 을 사용한다. 설명서를 보면 RegisterConverters 방법을 사용하여 사용자 정의 를 추가할 수 있다. 그러나 다음과 같은 몇 가지 문제가 있다. JavaScriptConverter는 사전을 연재한다. 즉, 사물을 가져다가 Json 사전을 연재한다. 객체를 문자열로 직렬화하려면 약간의 진부함이 필요하다( 참조 이 특별한 해킹은 또한 끈에서 벗어날 것이다.

public class CustomJsonResult : JsonResult
{
    private const string _dateFormat = "yyyy-MM-dd HH:mm:ss";

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        HttpResponseBase response = context.HttpContext.Response;

        if (!String.IsNullOrEmpty(ContentType))
        {
            response.ContentType = ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }
        if (ContentEncoding != null)
        {
            response.ContentEncoding = ContentEncoding;
        }
        if (Data != null)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            // Use your custom JavaScriptConverter subclass here.
            serializer.RegisterConverters(new JavascriptConverter[] { new CustomConverter });

            response.Write(serializer.Serialize(Data));
        }
    }
}

Approach 2 (recommended): The second approach is to start with the overridden JsonResult and go with another Json serializer, in my case the serializer. This doesn't require the hackery of approach 1. Here is my implementation of the JsonResult subclass:

 

번역: 

접근 2(권장): 두 번째 방법은 오버라이드된 JsonResult부터 시작해서 다른 Json serializer, 내 경우 serializer로 가는 것이다. 이것은 접근 1의 속임수를 필요로 하지 않는다. JsonResult 하위 클래스에 대한 구현:

 

public class CustomJsonResult : JsonResult
{
    private const string _dateFormat = "yyyy-MM-dd HH:mm:ss";

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        HttpResponseBase response = context.HttpContext.Response;

        if (!String.IsNullOrEmpty(ContentType))
        {
            response.ContentType = ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }
        if (ContentEncoding != null)
        {
            response.ContentEncoding = ContentEncoding;
        }
        if (Data != null)
        {
            // Using Json.NET serializer
            var isoConvert = new IsoDateTimeConverter();
            isoConvert.DateTimeFormat = _dateFormat;
            response.Write(JsonConvert.SerializeObject(Data, isoConvert));
        }
    }
}

Usage Example:

[HttpGet]
public ActionResult Index() {
    return new CustomJsonResult { Data = new { users=db.Users.ToList(); } };
}

 

매우매우 유용한 답변이다. Json은 date타입을 파싱하지 못하는데 클라이언트측에서해결하는 방식이 아닌 서버단에서 해결하는 방식으로 매우매우 유용하다. 

 

출처 : https://stackoverflow.com/questions/726334/asp-net-mvc-jsonresult-date-format

반응형

+ Recent posts