MVC: How to Return a String as JSON

后端 未结 5 416
刺人心
刺人心 2020-11-27 16:58

In an effort to make a progress reporting process a little more reliable and decouple it from the request/response, I am performing the processing in a Windows Service and p

相关标签:
5条回答
  • 2020-11-27 17:21

    Use the following code in your controller:

    return Json(new { success = string }, JsonRequestBehavior.AllowGet);
    

    and in JavaScript:

    success: function (data) {
        var response = data.success;
        ....
    }
    
    0 讨论(0)
  • 2020-11-27 17:25

    The issue, I believe, is that the Json action result is intended to take an object (your model) and create an HTTP response with content as the JSON-formatted data from your model object.

    What you are passing to the controller's Json method, though, is a JSON-formatted string object, so it is "serializing" the string object to JSON, which is why the content of the HTTP response is surrounded by double-quotes (I'm assuming that is the problem).

    I think you can look into using the Content action result as an alternative to the Json action result, since you essentially already have the raw content for the HTTP response available.

    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
    

    Another alternative would be to deserialize the JSON result from the service into an object and then pass that object to the controller's Json method, but the disadvantage there is that you would be de-serializing and then re-serializing the data, which may be unnecessary for your purposes.

    0 讨论(0)
  • 2020-11-27 17:27

    You just need to return standard ContentResult and set ContentType to "application/json". You can create custom ActionResult for it:

    public class JsonStringResult : ContentResult
    {
        public JsonStringResult(string json)
        {
            Content = json;
            ContentType = "application/json";
        }
    }
    

    And then return it's instance:

    [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);
    }
    
    0 讨论(0)
  • 2020-11-27 17:32

    Yeah that's it without no further issues, to avoid raw string json this is it.

        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
            };
        } 
    

    NOTE: please note that method return type of JsonResult is not working for me, since JsonResult and ContentResult both inherit ActionResult but there is no relationship between them.

    0 讨论(0)
  • 2020-11-27 17:39

    All answers here provide good and working code. But someone would be dissatisfied that they all use ContentType as return type and not JsonResult.

    Unfortunately JsonResult is using JavaScriptSerializer without option to disable it. The best way to get around this is to inherit JsonResult.

    I copied most of the code from original JsonResult and created JsonStringResult class that returns passed string as application/json. Code for this class is below

    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);
                }
            }
        }
    

    Example usage:

    var json = JsonConvert.SerializeObject(data);
    return new JsonStringResult(json);
    
    0 讨论(0)
提交回复
热议问题