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.

cool breeze
  • 4,461
  • 5
  • 38
  • 67
  • Use StringContent object as the `.Content` property of the HttpResponseMessage. See [this question](https://stackoverflow.com/questions/12240713/put-content-in-httpresponsemessage-object) – maccettura Mar 06 '18 at 18:10

1 Answers1

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;
}
David Lebee
  • 596
  • 4
  • 14