My problem is this:
This is the response being sent back from my WebAPI controller.
"[
[
{\"id\":\"identifier\"},
{\"name\":\"foobar\"}
]
]"
Notice that the response is wrapped in quotations and all of the embedded quotations are escaped. This is obviously a problem. Are there any settings I can provide to the JSON.NET Serializer to prevent this from occurring?
As p.s.w.g guessed in his response, I was using JSON.NET's
JsonConvert.SerializeObject(instance)
to perform my serialization.
I did this because as I was building out my custom Converters, I had included them in the JsonConvert.DefaultSettings within my WepApiConfig (and I obviously thought this would not be a problem)
I had previously tried to swap the return type of my HttpGets to "my object type" and the response was a json representation of my object's ToString() method...which let me know that serialization was not passing through my converters.
Changing the return type of my HttpGets from string to "my object type" and plugging those converters straight into WebAPi's default HttpConfiguration did the trick.
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new FooConverter());
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new BarConverter());
Easy peasy.
You probably have something like this:
public string GetFoobars()
{
var foobars = ...
return JsonConvert.SerializeObject(foobars);
}
In this case, you're serializing the object into string with Json.NET, then by returning the result as a string, the API controller will serialize the string as a JavaScript string literal—which will cause the string to be wrapped in double quotes and cause any other special characters inside the string to escaped with a backslash.
The solution is to simply return the objects by themselves:
public IEnumerable<Foobar> GetFoobars()
{
var foobars = ...
return foobars;
}
This will cause the API controller to serialize the objects using it's default settings, meaning it will serialize the result as XML or JSON depending on the parameters passed in from the client.
Further Reading
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With