Monday, June 3, 2024
Homepage · c#
 Popular · Latest · Hot · Upcoming
178
rated 0 times [  181] [ 3]  / answers: 1 / hits: 9740  / 10 Years ago, tue, january 13, 2015, 12:00:00

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?


More From » c#

 Answers
2

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.


[#40023] Monday, January 12, 2015, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hollievalerier

Total Points: 431
Total Questions: 93
Total Answers: 105

Location: Montenegro
Member since Thu, Jun 16, 2022
2 Years ago
hollievalerier questions
Mon, Jul 26, 21, 00:00, 3 Years ago
Fri, Mar 19, 21, 00:00, 3 Years ago
Thu, Jan 21, 21, 00:00, 3 Years ago
;