2

Question Background:

I am receiving a JSON string response from a HttpResponseMessage object via the Task ReadAsStringAsync method, as shown:

 string jsonString = response.Content.ReadAsStringAsync().Result;

This gives me the following escaped JSON:

"\"{\\\"A\\\":\\\"B\\\"}\""

The Question:

I believe that this is being escaped twice which mean I am trying to map this JSON to a C# POCO I am having via Newtonsoft to convert it to a string type, then to my desired object type, as shown:

  var model = JsonConvert.DeserializeObject<T>(JsonConvert.DeserializeObject<string>(response.Content.ReadAsStringAsync().Result));

Is there a way to stop this double escaping so I do not have to deserialize the JSON twice?

Dev
  • 153
  • 1
  • 10
  • 4
    Where do you see it being escaped twice? Are you using a Watch, highlighting over the variable when debugging, or writing to console/file? And what is the error you get when you call `DeserializeObject`? – ColinM Aug 30 '18 at 13:25
  • 1
    From where are you getting your json? Did you check your input with another tool, e.g. Postman? – ChristianMurschall Aug 30 '18 at 13:28
  • I suspect that the double encoding it just the ide being nice to you in the debugger preview. Scribble that text into c:/temp/1.txt and have a look, I bet it isn't really double encoded :) – Davesoft Aug 30 '18 at 13:35
  • You are probably inspecting the string by clicking on the magnifying glass which displays it as escaped twice. – Hozikimaru Aug 30 '18 at 13:42
  • `ReadAsStringAsync` (and related functions) don't do *any* escaping. If unexpected escaping *is* happening (heed the other comments), you need to look elsewhere. – Damien_The_Unbeliever Aug 30 '18 at 13:52
  • Possibly there is an error on the server side along the lines of [JSON.NET Parser *seems* to be double serializing my objects](https://stackoverflow.com/q/25559179/3744182). – dbc Aug 31 '18 at 22:41

0 Answers0