2

It's easy to serialize an object with members that are declared as interface types - we just set the following configuration:

JsonSerializerSettings settings = new JsonSerializerSettings()
            {                   
                TypeNameHandling = TypeNameHandling.Objects,
                TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple
            };

This will create a "fake property" $type for each object, and for interface-typed data, it will be the precise type that it actually was before serialization. This makes sense because the deserializer would need to know how to rebuild it, and there's no other sure-fire way to reconstruct it, especially if you've got interfaces that have the exact same properties but different function implementations.

The following question addresses this by inspecting a property value (to determine whether it's gonna be a Son or Daughter) in a custom converter, but we can't always do this. So, we're stuck with the Newtonsoft solution with $type.

There is also a question that removes the namespace of the value of $type, which helps (by shortening), but I still don't want to make the front-end have to write the $type "property" before it gets passed to an API call.

Essentially, I want the front-end not to care about $type but at the back end (or even in an API function), I want to work with my full object as if it was never serialized (and then deserialized). How should I design my interfaces and objects? What other Newtonsoft settings do I need to make?

Community
  • 1
  • 1
Mickael Caruso
  • 8,721
  • 11
  • 40
  • 72
  • 1
    In order to support polymorphic classes during deserialization, Json.Net needs some kind of indicator in the JSON as to what concrete type to instantiate. You can either use the built-in `$type` mechanism (`TypeNameHandling = TypeNameHandling.Objects`), or you can use a custom `JsonConverter` to handle the instantiation. Those are the two choices, unless you want to resort to weakly-typed objects (e.g. `JObject` or `dynamic`). When you say that you "can't always use a converter", what is standing in your way? – Brian Rogers Mar 25 '15 at 02:18
  • When I said "custom converter, but we can't always do this", I meant we can't always inspect that the object to be converted to a concrete type has a specific property. It looks like I'll go the JsonConverter route, and I recently found out that you can intercept the serialization process and add a property for "concrete type bookkeeping purposes" that isn't the default $type. – Mickael Caruso Mar 25 '15 at 15:05
  • 1
    Indeed, the same converter that reads the type indicator property on deserialization (sometimes called a "discriminator") can be made to add a such a property to the JSON on serialization. – Brian Rogers Mar 25 '15 at 17:06

0 Answers0