I would like the following Author type to have a default JsonConverter, and be able to override it at runtime.
[JsonConverter(typeof(BaseJsonConverter))] public class Author { // The ID of an author entity in the application. public int ID { set; get; } // The ID of an Author entity in its source. public string SourceID { set; set; } } I used the following code to override the default converter (i.e., BaseJsonConverter).
public class AlternativeConverter : BaseJsonConverter { // the serializer implementation is removed for clarity. } // Deserialize using AlternativeConverter: var author = JsonConvert.DeserializeObject<Author>(jsonString, new AlternativeConverter()); Question
Using the above call, the AlternativeConverter is first constructed; however, then an instance of BaseJsonConverter is initialized and used for deserialization. So, the AlternativeConverter is never used.
Executable example: https://dotnetfiddle.net/l0bgYO
Use case
The application is to convert different JSON objects, obtained from different sources, to a common C# type. Commonly data comes from a source for that we define the default converter (i.e., BaseJsonConverter), and for data coming from other sources, we define different converters per each.
Background
I am aware of methods such as this one, and indeed I am using similar method partially. With ref to that article, I need to have different _propertyMappings depending on the source of input, because in my application attribute to property mapping is not one-to-one. For instance, I have the following JSON objects:
{ "id":123 } // and { "id":"456" } where the first JSON object should be deserialized to:
author.ID = 123 author.SourceID = null and the second JSON object should be deserialized as:
author.ID = 0 author.SourceID = "456"
JTokenas the C# object that you need? Unless, I don't quite get your question, it seems like you're making your life difficult.Author. If you know that the incoming json is of typeAuthor, add[JsonProperty("blabla")]on top of each variable and parse it as aJTokenand C# will do the rest. Again, if I'm missing the point, do let me know.[JsonProperty("blabal")]. For instance, bothIDandSourceIDwill have[JsonProperty("id")], plz see the Json examples.