A back slash get added before the json string and throws issue with deserialization

Viewed 748

I have returned JSON data from the API call which when read as string from the HTTP response adds a backslash before the flower braces ({) in the start and end of the JSON string. Due to this while deserializing the JSON value to an object throws an exception.

I have read the string using the below code.

string value = await httpResponse.Content.ReadAsStringAsync();

And the result is

"\"{\"key\":null}\""**

Due to unwanted slashes added before after this curly braces, throws an exception in deserialization as JSON value could not be converted to the object type.

1 Answers

It seems the API you are requesting for the key response serializes the object to JSON twice or so. It usually gives the escaped string like you mentioned.

Try this:

var unescaped = JsonConvert.DeserializeObject<string>(value);
var key = JsonConvert.DeserializeObject<MyKeyClass>(unescaped);

Assuming your MyKeyClass is something like this:

public class MyKeyClass {
   public string Key { get; set; }
}
Related