source

ASP의 Json()에서 소문자 속성 이름을 강제로 지정합니다.넷 MVC

nicesource 2023. 3. 10. 22:07
반응형

ASP의 Json()에서 소문자 속성 이름을 강제로 지정합니다.넷 MVC

다음 수업에서

public class Result
{      
    public bool Success { get; set; }

    public string Message { get; set; }
}

이렇게 컨트롤러 액션으로 이것들 중 하나를 반품합니다.

return Json(new Result() { Success = true, Message = "test"})

그러나 클라이언트 측 프레임워크에서는 이러한 속성이 소문자로 성공하고 메시지가 표시될 것으로 예상합니다.실제로 소문자 속성 이름을 사용할 필요가 없는 것이 일반적인 Json 함수 호출을 활성화하는 방법입니까?

이를 실현하는 방법은 다음과 같은 커스텀을 구현하는 것입니다.JsonResult 를 들어 커스텀 ValueType을 생성하여 커스텀 JsonResult를 사용시리얼화(원래 링크 데드).

JSON과 같은 대체 시리얼 라이저를 사용합니다.NET, 이러한 동작을 서포트합니다.다음은 예를 제시하겠습니다.

Product product = new Product
{
  ExpiryDate = new DateTime(2010, 12, 20, 18, 1, 0, DateTimeKind.Utc),
  Name = "Widget",
  Price = 9.99m,
  Sizes = new[] {"Small", "Medium", "Large"}
};

string json = 
  JsonConvert.SerializeObject(
    product,
    Formatting.Indented,
    new JsonSerializerSettings 
    { 
      ContractResolver = new CamelCasePropertyNamesContractResolver() 
    }
);

결과:

{
  "name": "Widget",
  "expiryDate": "\/Date(1292868060000)\/",
  "price": 9.99,
  "sizes": [
    "Small",
    "Medium",
    "Large"
  ]
}

웹 API를 사용하는 경우 시리얼라이저를 변경하는 것은 간단하지만 불행히도 MVC 자체는JavaScriptSerializerJSON을 사용하도록 변경할 수 없습니다.그물.

James의 답변과 Daniel의 답변은 JSON의 유연성을 제공합니다.네트워크(Net)는 일반적으로 사용하는 모든 장소에서return Json(obj)로 갈아타야 합니다.return new JsonNetResult(obj)또는 대규모 프로젝트가 있는 경우 문제가 발생할 수 있으며 사용하려는 시리얼라이저에 대한 생각이 바뀌면 유연성이 떨어집니다.


난 내려가기로 결심했어ActionFilter다음 코드를 사용하여 다음 작업을 수행할 수 있습니다.JsonResultJSON을 사용하기 위해 Atribute를 적용하기만 하면 됩니다.넷(소문자 속성 포함):

[JsonNetFilter]
[HttpPost]
public ActionResult SomeJson()
{
    return Json(new { Hello = "world" });
}

// outputs: { "hello": "world" }

모든 액션에 자동으로 적용되도록 설정할 수도 있습니다(하드웨어의 퍼포먼스에 미치는 영향은 경미함).is체크) :

FilterConfig.cs

// ...
filters.Add(new JsonNetFilterAttribute());

코드

public class JsonNetFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext.Result is JsonResult == false)
            return;

        filterContext.Result = new CustomJsonResult((JsonResult)filterContext.Result);
    }

    private class CustomJsonResult : JsonResult
    {
        public CustomJsonResult(JsonResult jsonResult)
        {
            this.ContentEncoding = jsonResult.ContentEncoding;
            this.ContentType = jsonResult.ContentType;
            this.Data = jsonResult.Data;
            this.JsonRequestBehavior = jsonResult.JsonRequestBehavior;
            this.MaxJsonLength = jsonResult.MaxJsonLength;
            this.RecursionLimit = jsonResult.RecursionLimit;
        }

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

            if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet
                && String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
                throw new InvalidOperationException("GET not allowed! Change JsonRequestBehavior to AllowGet.");

            var response = context.HttpContext.Response;

            response.ContentType = String.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;

            if (this.ContentEncoding != null)
                response.ContentEncoding = this.ContentEncoding;

            if (this.Data != null)
            {
                var json = JsonConvert.SerializeObject(
                    this.Data,
                    new JsonSerializerSettings
                        {
                            ContractResolver = new CamelCasePropertyNamesContractResolver()
                        });

                response.Write(json);
            }
        }
    }
}

내 솔루션을 사용하면 원하는 모든 속성의 이름을 바꿀 수 있습니다.

솔루션의 일부를 여기서도, 또 여러 곳에서 찾았습니다.

public class JsonNetResult : ActionResult
    {
        public Encoding ContentEncoding { get; set; }
        public string ContentType { get; set; }
        public object Data { get; set; }

        public JsonSerializerSettings SerializerSettings { get; set; }
        public Formatting Formatting { get; set; }

        public JsonNetResult(object data, Formatting formatting)
            : this(data)
        {
            Formatting = formatting;
        }

        public JsonNetResult(object data):this()
        {
            Data = data;
        }

        public JsonNetResult()
        {
            Formatting = Formatting.None;
            SerializerSettings = new JsonSerializerSettings();
        }

        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;

            var writer = new JsonTextWriter(response.Output) { Formatting = Formatting };
            var serializer = JsonSerializer.Create(SerializerSettings);
            serializer.Serialize(writer, Data);
            writer.Flush();
        }
    }

그래서 내 컨트롤러로, 나는 그것을 할 수 있다.

        return new JsonNetResult(result);

모델에서는 다음과 같은 기능이 있습니다.

    [JsonProperty(PropertyName = "n")]
    public string Name { get; set; }

이 시점에서, 다음의 설정을 실시할 필요가 있는 것에 주의해 주세요.JsonPropertyAttribute원하는 모든 재산으로 이동할 수 있습니다.

비록 오래된 질문이지만, 아래의 코드 조각이 다른 사람들에게 도움이 되기를 바랍니다.

MVC5 Web API로 아래와 같이 했습니다.

public JsonResult<Response> Post(Request request)
    {
        var response = new Response();

        //YOUR LOGIC IN THE METHOD
        //.......
        //.......

        return Json<Response>(response, new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() });
    }

이 설정을 다음에 추가할 수 있습니다.Global.asax어디에서나 사용할 수 있습니다.

public class Global : HttpApplication
{   
    void Application_Start(object sender, EventArgs e)
    {
        //....
         JsonConvert.DefaultSettings = () =>
         {
             var settings = new JsonSerializerSettings
             {
                 ContractResolver = new CamelCasePropertyNamesContractResolver(),
                 PreserveReferencesHandling = PreserveReferencesHandling.None,
                 Formatting = Formatting.None
             };

             return settings;
         }; 
         //....
     }
}

언급URL : https://stackoverflow.com/questions/2789593/force-lowercase-property-names-from-json-in-asp-net-mvc

반응형