0

I have a aspnet web api that returns json using this code:

Project_Model mdl = new Project_Model(transactionId, data);
string json = string.Empty;
json = JsonConvert.SerializeObject(mdl);

and this is the value of the variable “json”:

{\"Pj_Id\":\"23a6bd47-c35a-4ee3-8998-bd0406bc5839\",\"Pj_CUsr_Id\":\"8cb52c3e-25b7-412d-8010-cadd75f1f64b\",\"Pj_Number\":\"test 101\",\"Pj_Name\":\"Test Project 101\",\"Pj_Location\":\"1551 Main St, Houston\"}

But it should look like this:

{
  "Pj_Id": "23a6bd47-c35a-4ee3-8998-bd0406bc5839",
  "Pj_CUsr_Id": "8cb52c3e-25b7-412d-8010-cadd75f1f64b",
  "Pj_Number": "test 101",
  "Pj_Name": "Test Project 101",
  "Pj_Location": "1551 Main St, Houston"
}    

I know we will get escape characters like this in the debugger but not in the output. The example above with the backslashes was copied from PostMan’s output of the same API.

Can someone please tell me why this is happening and what can be done to clean it up?

Thanks.

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
spacedog
  • 446
  • 3
  • 13
  • 4
    You know that ASP.NET will serialize what you return from it, right? You're probably serializing the JSON yourself and then returning it in a way that causes ASP.NET to also serialize it. – ProgrammingLlama Jul 15 '21 at 07:32
  • Ideally you shouldn't be serialising the JSON yourself as it's likely it's being double serialised. Just return `mdl` from the ASP.Net Web API action method instead of the JSON. – phuzi Jul 15 '21 at 07:40

1 Answers1

2

@phuzi was correct in the comment above:

Ideally you shouldn't be serializing the JSON yourself as it's likely it's being double serialized. Just return mdl from the ASP.Net Web API action method instead of the JSON

I was double serializing it. I just returned the class and it came out perfect json.

Thanks.

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
spacedog
  • 446
  • 3
  • 13