JSON.NET Serialization behaves differently in ApiController

We are using JSON.NET to serialize custom objects. I wrote a unit test that successfully serializes the JSON of our custom object:

// Generate custom object...
var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }; // Serializing objects referred to by abstract type, see comment at http://www.tomdupont.net/2014/04/deserialize-abstract-classes-with.html
var json = JsonConvert.SerializeObject(object, settings);
// ...Deserialize object and compare are equal

      

However, in our APIController that handles HTTP requests and has methods like this:

[HttpPost]
public ActionResult ProfileFile()
{
    // Code to handle HTTP request
}

      

performing the same serialization operation on a custom object generated in the same way yields a stream System.InvalidCastException

for custom objects in the serialized custom object (all of which are tagged with JSON.NET attributes and have their own passing test block).

What could cause it to behave differently in our web project while it is running in unit tests? Thanks in advance.

+3


source to share


1 answer


Without knowing the exact content of the object you are trying to serialize, it is difficult to provide an exact solution. However, if I was in your situation, I would create a rudimentary class that represents your custom object and try to serialize it. If you keep seeing this error, I would start adding the JsonIgnore attribute to various properties of the class to see which property is actually causing this failure. This will help you narrow down the problem.



0


source







All Articles