如何通过ActionResult公开JSON对象数组

时间:2012-02-02 01:35:53

标签: asp.net-mvc json

我有以下代码:

private ActionResult Foo(string format, IEnumerable<String> myResults)
    {
        if (format == "JSON")
        {
            return ConvertToAnJsonActionResult(myResults); // GetJsonResults(sm);
        }
        else //turn to html and return
        {
            return View("Index", myResults);
        }
    }

myResults是JSON字符串的集合。我需要将其转换为包含JSON数组并将其发送到客户端的ActionResult。我该怎么做?

我尝试了return Json(myResults),它返回了一个JsonResult,但后来我编写了一个JSON对象集合的JSON,这将导致在客户端获得结果时将“添加到每个”。

4 个答案:

答案 0 :(得分:1)

返回JsonResult将完成工作。 JsonResult继承了ActionResult,你可以查看这个链接。 ActionResults

答案 1 :(得分:1)

我最终重写了JsonResult:

public class ArrayJsonResult : System.Web.Mvc.JsonResult
{
    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("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)
        {
            StringWriter sw = new StringWriter();
            sw.Write("[");
            try
            {
                var collection = Data as IEnumerable<String>;
                int countLessOne = collection.Count() -1;
                for (int i = 0; i < countLessOne; i++ )
                {
                    sw.Write(collection.ElementAt(i));
                    sw.Write(",");
                }
                sw.Write(collection.ElementAt(countLessOne));
            }
            catch (Exception)
            {
                //data was not a collection
            }

            sw.Write("]");
            response.Write(sw.ToString());
        }
    }

答案 2 :(得分:0)

返回JsonResult而不是ActionResult

快速谷歌搜索出现了这篇博文......

http://shashankshetty.wordpress.com/2009/03/04/using-jsonresult-with-jquery-in-aspnet-mvc/

答案 3 :(得分:0)

由于任何内置方法都不支持混合json和non-json,最好的办法是手动构建并返回json数组:

return Content( 
    myResults.Aggregate(
        new StringBuilder("[\""),
        (sb,r) => sb.Append(r).Append('","'),
        sb => sb.RemoveAt(sb.Length-2,2).Append("]").ToString()
    ),
    "application/json" 
);