1

How can I take control of the JSON serialization and not have web API serialize my model?

Currently the resulting string is double serialized because I am doing it AND web api is performing it.

public HttpResponseMessage GetUsers()
{
    var users = _service.GetUsers()
    var model = new UserResponse(users);

    var json = JsonConvert.SerializeObject(model);


    return Request.CreateResponse(HttpStatusCode.OK, json, Configuration.Formatters.JsonFormatter);
}

I am going to add some customization so I need to take control of this JSON serialization part.

1
  • Use StringContent object as the .Content property of the HttpResponseMessage. See this question Commented Mar 6, 2018 at 18:10

1 Answer 1

4

You can try this

public HttpResponseMessage GetUsers()
{
    var users = _service.GetUsers()
    var model = new UserResponse(users);

    var json = JsonConvert.SerializeObject(model);
    var response = this.Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new StringContent(json , Encoding.UTF8, "application/json");
    return response
}

or

public IHttpActionResult GetUsers()
{
    var users = _service.GetUsers()
    var model = new UserResponse(users);
    return Ok(model);
}

or

public UserResponse GetUsers() 
{
    var users = _service.GetUsers()
    var model = new UserResponse(users);
    return model;
}
Sign up to request clarification or add additional context in comments.

Comments

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.