JSON.NET double serialization problem
When using JSON.NET to serialize objects, you may encounter a strange problem: the object is double-serialized. This causes the JSON data in the response to be wrapped in double quotes, and embedded quotes to be escaped.
Root Cause
The root of the problem lies in the serialization method. If you use JsonConvert.SerializeObject(instance)
like in the example, the object will be serialized twice. This is because you serialize it to a string first, and then the API controller further serializes it to a JavaScript string literal.
Solution
To fix this, just return the object directly:
<code class="language-csharp">public IEnumerable<foobar> GetFoobars() { var foobars = ...; return foobars; }</code>
Alternative methods
Alternatively, you can choose to add a custom converter directly to the Web API's default HttpConfiguration
:
<code class="language-csharp">config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new FooConverter()); config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new BarConverter());</code>
Other Tips
The above is the detailed content of Why is JSON.NET Double Serializing My Objects?. For more information, please follow other related articles on the PHP Chinese website!