1

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.

4
  • then do not return string but model(Data) Commented Nov 16, 2018 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 Commented Nov 16, 2018 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 Commented Nov 16, 2018 at 12:21
  • Yes you are all right, should have known that. I fixed it in my code and it works perfectly. Thanx alot! Commented Nov 19, 2018 at 8:28

1 Answer 1

1

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; 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanx for the explaining, i fixed it and it works perfectly

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.