1

I have a c# method that calls another method which returns back a string that is supposed to represent JSON. However, the string has escape characters in it:

public string GetPerson()
{
  string person = repo.GetPerson(); //person is  "{\"name\":jack,\"age\":\"54\"...
  return person;            
}

If I try to do a replace, there is no change:

string person = repo.GetPerson().Replace(@"\""", ""); //person still has escape characters

When I try to view person in the text viewer when debugging, the escape characters are not there--Visual Studio rips them off. But my javascript that calls this method does see the escape characters in the ajax response.

If I try to deserialize the person string into my C# User object, it does not deserialize properly:

User user = JsonConvert.DeserializeObject<User>(person);

What are my options? How can I either strip off the escape characters from the person string, or deserialize it correctly to the User object?

1
  • What are you using to serialize and pass the JSON? Commented Jan 13, 2015 at 23:20

1 Answer 1

3

If a Console.WriteLine(person) shows those backslashes and quotes around the string (not just the string and quotes inside), then there is a double serialization issue. You could try first to deserialize it to a string, then to a type, like this:

User user = JsonConvert.DeserializeObject<User>(JsonConvert.DeserializeObject<String>(person));

Also, you could try to do:

string person = repo.GetPerson().Replace(@"\""", @"""");

If you have control over the API, check for double serialization on return. ASP does a default serialization, so usually you don't have to return a string with the object pre-serialized.

For webapi, use Ok(object), for ASP MVC, use Json(object, requestBehaviour) methods.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. It seemed to be a case of double serialization.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.