Troubleshooting JSON.NET Serialization in WebAPI
A frequent problem encountered when using JSON.NET with Web API involves responses unexpectedly wrapped in double quotes, with internal quotes escaped. This often stems from directly using JsonConvert.SerializeObject
. The solution is to avoid explicit serialization.
Instead of this:
<code class="language-csharp">public string GetFoobars() { var foobars = ...; return JsonConvert.SerializeObject(foobars); }</code>
Return the object directly:
<code class="language-csharp">public IEnumerable<Foobar> GetFoobars() { var foobars = ...; return foobars; }</code>
By omitting the explicit serialization, the Web API controller leverages its built-in serialization mechanisms (either XML or JSON, determined by the client request). This approach effectively prevents the unwanted double quoting and escape character issues.
The above is the detailed content of Why is my JSON.NET serialized WebAPI response enclosed in double quotes, and how can I fix it?. For more information, please follow other related articles on the PHP Chinese website!