0

I have a model "data" which contains some booleans and strings. I want this model returned with a HttpResponseMessage. Currently I am doing it like this:

string JSON = JsonConvert.SerializeObject(Data);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, JSON);
return response;

This results in the following JSON output "{\"\"}". But I need it to be {""}. Yet if I only show the JSON before the HttpResponseMessage it is like {""} and I don't seem to find out what causes the output format to change. Does anyone know what causes this and how to solve this? It seems to me the JSON gets 'stringitized' but why I don't know.

I am using NewtonSoft.

user247702
  • 23,641
  • 15
  • 110
  • 157
M Menne
  • 11
  • 1
  • then do not return string but model(Data) – Selvin Nov 16 '18 at 12:04
  • The backslash character is indicating that the quote has been escaped. If you are seeing that in the debugger then it would be normal to see that – Martin Nov 16 '18 at 12:04
  • *try this => string JSON (... and the code to serialize object to string then deserialize it back)* **NO, do not try .... it is useless code** ... obviously simple `return Request.CreateResponse(HttpStatusCode.OK, Data);` will do the thing – Selvin Nov 16 '18 at 12:21
  • Yes you are all right, should have known that. I fixed it in my code and it works perfectly. Thanx alot! – M Menne Nov 19 '18 at 08:28

1 Answers1

0

This happens because the Web API framework has built-in serialization, and you are manually serializing your data on top of that. This double-serialization results in the extra backslashes and quotes you see in the response JSON.

To fix your code, remove the call to SerializeObject and pass your Data object directly to Request.CreateResponse like this:

HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, Data);
return response;
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300