JSON.NET Parser *seems* to be double serializing my objects

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

Leave a Comment