I've written my first REST API service via my ASP.Net 4.5.2 Web Application, which accept JSON data (via POST) and returns JSON data.
When I call the service using PowerShell, the returned JSON is exactly as required, and using $returnData | ConvertTo-Json works as expected allowing access to the object...
{"result":"ok"} But when I call the service using RestMan on Chrome the result appears to be double-encoded...
"{\"result\":\"ok\"}" I've also checked the developer tools in Chrome and the response tab shows this double-encoding, despite the response header containing Content-Type: application/json; charset=utf-8... which says to me this isn't a problem with RestMan, but my gut feeling is that it isn't an issue with Chrome either.
I've breakpointed on the final Return in the code, and the return string is definitely correct... it is not double-encoded.
I am not specifically setting the content type, .Net appears to be doing that for me, but I've tried setting it via HttpContext.Current.Response.ContentType and it doesn't make any difference.
What am I doing wrong?!
Invoice-RestMethodwhich already handles JSON for you (unlikeInvoke-WebRequest) and once by another manual call toConvertFrom-Json?Acceptheader was sent), and maybe you additionally callJsonSerializer.Serializeand encode it a second time...JsonSerializer.serializeon it, turning it into a string. Then you return it, and ASP.NET JSON-encodes your string, resulting in a double-encoded object string.Invoke-RestMethodreceives that string and decodes it, resulting in the original once-encoded string representation of the object, and you then callConvertFrom-Jsonto resolve that second layer of encoding, getting back the original object.I'm definitely not calling a 2nd Serialize<< from your perspective it'd be the 1st - which is apparent from your stating that it isreturning a string already! It is returning it to ASP.NET which will nicely encode it for you to send your value as JSON... Which already was JSON before, since you serialized it manually (unnecessarily). That's what I thinkInvoke-RestMethodauto-decodes for you. So no need to manually encode or decode anything, otherwise it ends up getting encoded twice, which seems to be what happened here. You can just return an object. - I'm pretty convinced now that this is what's going on, so I'll turn it into an answer