programing

MVC Json Result camel Case 시리얼화

codeshow 2023. 3. 23. 23:01
반응형

MVC Json Result camel Case 시리얼화

모든 속성이 camelCase에 있는 JsonResult를 반환하려고 합니다.

심플한 모델이 있습니다.

public class MyModel
{
    public int SomeInteger { get; set; }

    public string SomeString { get; set; }
}

간단한 컨트롤러 동작:

public JsonResult Index()
    {
        MyModel model = new MyModel();
        model.SomeInteger = 1;
        model.SomeString = "SomeString";

        return Json(model, JsonRequestBehavior.AllowGet);
    }

이 액션 메서드를 호출하면 다음 데이터가 포함된 JsonResult가 반환됩니다.

{"SomeInteger":1,"SomeString":"SomeString"}

사용을 위해 다음과 같은 방법으로 camelCase에 데이터를 반환해야 합니다.

{"someInteger":1,"someString":"SomeString"}

우아한 방법이 없을까요?

이 근처에서 가능한 솔루션을 찾고 있었는데, MVC3 JSON Serialization을 발견했습니다. 속성 이름을 제어하려면 어떻게 해야 합니까?DataMember 정의를 모델의 모든 속성에 설정하지만, 이 작업은 하고 싶지 않습니다.

또, 이러한 문제를 정확하게 해결할 수 있다고 하는 링크도 찾았습니다.http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization#json_camelcasing다음과 같이 되어 있습니다.

데이터 모델을 변경하지 않고 캐멀케이스를 사용하여 JSON 속성 이름을 쓰려면 시리얼라이저에서 CamelCasePropertyNamesContractResolver를 설정합니다.

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

이 블로그 http://frankapi.wordpress.com/2012/09/09/going-camelcase-in-asp-net-mvc-web-api/의 한 엔트리에서도 이 솔루션에 대해 언급하고 있으며 단순히 RouteConfig에 추가할 수 있다고 기재되어 있습니다.RegisterRoutes를 사용하여 이 문제를 해결합니다.시도해 봤지만 잘 되지 않았어요.

내가 어디서 뭘 잘못했는지 알아?

동작에서 camelcase 표기법에 준거한json 문자열을 반환하려면 JsonSerializerSettings 인스턴스를 생성하여 JsonConvert의 두 번째 파라미터로 전달해야 합니다.Serialize Object(a, b) 메서드.

public string GetSerializedCourseVms()
    {
        var courses = new[]
        {
            new CourseVm{Number = "CREA101", Name = "Care of Magical Creatures", Instructor ="Rubeus Hagrid"},
            new CourseVm{Number = "DARK502", Name = "Defence against dark arts", Instructor ="Severus Snape"},
            new CourseVm{Number = "TRAN201", Name = "Transfiguration", Instructor ="Minerva McGonal"}
        };
        var camelCaseFormatter = new JsonSerializerSettings();
        camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();
        return JsonConvert.SerializeObject(courses, camelCaseFormatter);
    }

컨트롤러의 Json 함수는 JsonResults를 작성하기 위한 래퍼에 불과합니다.

protected internal JsonResult Json(object data)
{
    return Json(data, null /* contentType */, null /* contentEncoding */, JsonRequestBehavior.DenyGet);
}

protected internal JsonResult Json(object data, string contentType)
{
    return Json(data, contentType, null /* contentEncoding */, JsonRequestBehavior.DenyGet);
}

protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding)
{
    return Json(data, contentType, contentEncoding, JsonRequestBehavior.DenyGet);
}

protected internal JsonResult Json(object data, JsonRequestBehavior behavior)
{
    return Json(data, null /* contentType */, null /* contentEncoding */, behavior);
}

protected internal JsonResult Json(object data, string contentType, JsonRequestBehavior behavior)
{
    return Json(data, contentType, null /* contentEncoding */, behavior);
}

protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
{
    return new JsonResult
    {
        Data = data,
        ContentType = contentType,
        ContentEncoding = contentEncoding,
        JsonRequestBehavior = behavior
    };
}

JsonResult는 내부적으로 JavaScriptSerializer를 사용하므로 직렬화 프로세스를 제어할 수 없습니다.

public class JsonResult : ActionResult
{
    public JsonResult()
    {
        JsonRequestBehavior = JsonRequestBehavior.DenyGet;
    }

    public Encoding ContentEncoding { get; set; }

    public string ContentType { get; set; }

    public object Data { get; set; }

    public JsonRequestBehavior JsonRequestBehavior { get; set; }

    /// <summary>
    /// When set MaxJsonLength passed to the JavaScriptSerializer.
    /// </summary>
    public int? MaxJsonLength { get; set; }

    /// <summary>
    /// When set RecursionLimit passed to the JavaScriptSerializer.
    /// </summary>
    public int? RecursionLimit { get; set; }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }
        if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
            String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
        {
            throw new InvalidOperationException(MvcResources.JsonRequest_GetNotAllowed);
        }

        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();
            if (MaxJsonLength.HasValue)
            {
                serializer.MaxJsonLength = MaxJsonLength.Value;
            }
            if (RecursionLimit.HasValue)
            {
                serializer.RecursionLimit = RecursionLimit.Value;
            }
            response.Write(serializer.Serialize(Data));
        }
    }
}

JsonResult를 직접 만들고 Json 컨트롤러 함수를 직접 작성해야 합니다(필요하거나 원하는 경우).새로운 것을 작성하거나 기존의 것을 덮어쓸 수 있습니다.그것은, 유저에게 달려 있습니다.이 링크에도 관심이 있을 수 있습니다.

언급URL : https://stackoverflow.com/questions/15040838/mvc-jsonresult-camelcase-serialization

반응형