10

How to output a json object of Request.CreateResponse method?

the below code output the json string

    "{RowCount:15}"

,the string is not a json ojbect,it should use eval() method of javscript to convert to json object ,I want the server side return the json object directly, It should return

{RowCount:15}

that's a json object.

Code

public class PagedDataAttribute : ActionFilterAttribute
{

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        string jsonRowCount = "{RowCount:10}";
        actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(System.Net.HttpStatusCode.OK, jsonRowCount,System.Net.Http.Formatting.JsonMediaTypeFormatter.DefaultMediaType);
    }

}

1 Answer 1

29

Instead of using a string, use an anonymous object:

public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
    var rowCount = new { RowCount = 10 };
    actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(
        HttpStatusCode.OK,
        rowCount,
        JsonMediaTypeFormatter.DefaultMediaType
    );
}
Sign up to request clarification or add additional context in comments.

1 Comment

Holy Moly. For future readers and searchers, I was (errantly) doing this: JObject jo = /* Some Code that created JObject / string outputJsonContent = jo.ToString(Formatting.None); HttpResponseMessage resp = req.CreateResponse(HttpStatusCode.OK, outputJsonContent, new JsonMediaTypeFormatter()); I should have been doing this : (as this answer says) JObject jo = / Some Code that created JObject / HttpResponseMessage resp = req.CreateResponse(HttpStatusCode.OK, jo, new JsonMediaTypeFormatter()); / FYI #region Assembly Newtonsoft.Json, Version=9.0.0.0 : Newtonsoft.Json.Linq.JObject */

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.