MVC: 문자열을 JSON으로 되돌리는 방법
진척 보고서 프로세스의 신뢰성을 높이고 요구/응답에서 분리하기 위해 Windows Service에서 처리를 수행하여 파일에 대한 응답을 유지하고 있습니다.클라이언트가 업데이트 폴링을 시작하면 컨트롤러가 파일 내용을 JSON 문자열로 반환하는 것을 의도하고 있습니다.
파일의 내용은 JSON에 사전 직렬화됩니다.이는 응답에 방해가 되는 것이 없음을 확인하기 위한 것입니다.응답을 얻기 위해 파일 내용을 문자열로 읽고 반환하는 것 이외에는 처리할 필요가 없습니다.
처음에는 매우 간단하다고 생각했지만, 실제로는 그렇지 않습니다.
현재 컨트롤러 방식은 다음과 같습니다.
컨트롤러
갱신필
[HttpPost]
public JsonResult UpdateBatchSearchMembers()
{
string path = Properties.Settings.Default.ResponsePath;
string returntext;
if (!System.IO.File.Exists(path))
returntext = Properties.Settings.Default.EmptyBatchSearchUpdate;
else
returntext = System.IO.File.ReadAllText(path);
return this.Json(returntext);
}
그리고 피들러는 이것을 미가공의 응답으로 돌려보냈다.
HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Mon, 19 Mar 2012 20:30:05 GMT
X-AspNet-Version: 4.0.30319
X-AspNetMvc-Version: 3.0
Cache-Control: private
Content-Type: application/json; charset=utf-8
Content-Length: 81
Connection: Close
"{\"StopPolling\":false,\"BatchSearchProgressReports\":[],\"MemberStatuses\":[]}"
에이잭스
갱신필
다음 내용은 나중에 변경될 것 같습니다만, 일단은 일반인과 마찬가지로 응답 클래스를 생성하여 JSON으로 되돌리는 동안 이 작업이 진행되었습니다.
this.CheckForUpdate = function () {
var parent = this;
if (this.BatchSearchId != null && WorkflowState.SelectedSearchList != "") {
showAjaxLoader = false;
if (progressPending != true) {
progressPending = true;
$.ajax({
url: WorkflowState.UpdateBatchLink + "?SearchListID=" + WorkflowState.SelectedSearchList,
type: 'POST',
contentType: 'application/json; charset=utf-8',
cache: false,
success: function (data) {
for (var i = 0; i < data.MemberStatuses.length; i++) {
var response = data.MemberStatuses[i];
parent.UpdateCellStatus(response);
}
if (data.StopPolling = true) {
parent.StopPullingForUpdates();
}
showAjaxLoader = true;
}
});
progressPending = false;
}
}
문제는 Json 액션 결과가 오브젝트(모델)를 가져와 모델 오브젝트에서 JSON 형식의 데이터로 콘텐츠를 포함하는 HTTP 응답을 생성하는 것이라고 생각합니다.
단, 컨트롤러의 Json 메서드에 전달되는 것은 JSON 형식의 문자열 객체이므로 문자열 객체를 JSON에 "시리얼화"하고 있습니다.이 때문에 HTTP 응답의 내용은 이중 따옴표로 둘러싸여 있습니다(그것이 문제라고 생각됩니다).
기본적으로는 HTTP 응답에 사용할 수 있는 원시 콘텐츠가 있기 때문에 Json 액션 결과의 대안으로 Content 액션 결과를 사용하는 것을 검토해 볼 수 있다고 생각합니다.
return this.Content(returntext, "application/json");
// not sure off-hand if you should also specify "charset=utf-8" here,
// or if that is done automatically
또 다른 방법은 서비스로부터의 JSON 결과를 오브젝트로 역직렬화한 후 그 오브젝트를 컨트롤러의 Json 메서드에 전달하는 것입니다.단, 단점은 데이터의 시리얼화를 해제하고 다시 시리얼화하는 것입니다.이는 목적에 따라서는 불필요할 수 있습니다.
표준 Content Result를 반환하고 Content를 설정하기만 하면 됩니다.application/json 이라고 입력합니다.커스텀 Action Result를 생성할 수 있습니다.
public class JsonStringResult : ContentResult
{
public JsonStringResult(string json)
{
Content = json;
ContentType = "application/json";
}
}
그런 다음 인스턴스를 반환합니다.
[HttpPost]
public JsonResult UpdateBatchSearchMembers()
{
string returntext;
if (!System.IO.File.Exists(path))
returntext = Properties.Settings.Default.EmptyBatchSearchUpdate;
else
returntext = Properties.Settings.Default.ResponsePath;
return new JsonStringResult(returntext);
}
네, 더 이상 문제가 없습니다. raw string json을 피하려면 이겁니다.
public ActionResult GetJson()
{
var json = System.IO.File.ReadAllText(
Server.MapPath(@"~/App_Data/content.json"));
return new ContentResult
{
Content = json,
ContentType = "application/json",
ContentEncoding = Encoding.UTF8
};
}
주의: 메서드 반환 유형은 다음과 같습니다.JsonResult
안 먹혀요.JsonResult
★★★★★★★★★★★★★★★★★」ContentResult
상속하다ActionResult
하지만 그들 사이에는 아무런 관계가 없습니다.
컨트롤러에서 다음 코드를 사용합니다.
return Json(new { success = string }, JsonRequestBehavior.AllowGet);
및 JavaScript:
success: function (data) {
var response = data.success;
....
}
여기의 모든 답변은 정상 작동 코드를 제공합니다.가 '불만족'을 사용하는 것에 대해 수 .ContentType
으로서 「」이 , 「」라고 하는 것이 됩니다.JsonResult
도 ★★★★★★★★★★★★★★★.JsonResult
를 사용하고 .JavaScriptSerializer
디세블로 할 수 없습니다. 좋은 은 '상속'을 하는 입니다.JsonResult
.
의 코드를 .JsonResult
작성했습니다.JsonStringResult
하는 .application/json
public class JsonStringResult : JsonResult
{
public JsonStringResult(string data)
{
JsonRequestBehavior = JsonRequestBehavior.DenyGet;
Data = data;
}
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("Get request is not allowed!");
}
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)
{
response.Write(Data);
}
}
}
사용 예:
var json = JsonConvert.SerializeObject(data);
return new JsonStringResult(json);
언급URL : https://stackoverflow.com/questions/9777731/mvc-how-to-return-a-string-as-json
'programing' 카테고리의 다른 글
추가 대신 Ajax 교체 (0) | 2023.03.07 |
---|---|
Wordpress wpdb 정의되지 않은 변수 (0) | 2023.03.07 |
Wordpress에서 Facebook 세션 가져오기 (0) | 2023.03.02 |
프로젝터를 실행할 수 없음 - ECONNREFUSED 연결 ECONNREFUSED (0) | 2023.03.02 |
모든 기존 사용자에 대한 Wordpress 기본 표시 이름 변경 공개 (0) | 2023.03.02 |