My team was faced with an interesting challange where the shape of an object changed in a JSON collection. The collection only consisted of a few items but the shape was not consistent which broke the deserialization.
The example below consists of a JSON payload with 2 items, the common properties are Id, ProductType, ShortDescription. Each then have a unique property of Foo and Bar respectively.
1 2 3 4 5 6 7 8 9 10 11
[{ "Id":"511d1dda-3c62-47e1-9197-c84564f39520", "ProductType":"XML 2 SMS", "ShortDescription":"Designed for developers, the XML / HTTP interface will allow you to send and receive SMS messages and query current and historical logs using HTTP request and XML response.", "Foo":"Some foo property" },{ "Id":"1f2bd60f-8fe8-4e55-aebd-fa50e2b51086", "ProductType":"SMPP 2 SMS", "ShortDescription":"SMPP (Short Message Peer to Peer) is an industry standard form of connection for SMS Messaging.", "Bar":"Some bar property" }]
Solution (God Object)
Typically this could be deserialized to an object that has all of the properties mashed together and anything that doesnt exist in the payload will get the default value (normally null)
1
var myDeserializedClass = JsonConvert.DeserializeObject<SmsProduct>(myJsonResponse);
This is more complex and if you are a API provider this may cause your consumers headache. The flow of the custom serilizer at a high level would be:
Identify a Discriminator, this is something common to all the entities where discrimination can be applied. For the JSON example above this would be ProductType as we have two options that should repeat over the collection:
The microsoft example then does the some validations on the Utf8JsonReader reader, I have substituted with my example values and between the property checks the reader needs to be advanced with reader.Read();
1 2 3 4 5 6 7 8 9 10 11 12
if (reader.TokenType != JsonTokenType.StartObject) thrownew JsonException();
if (reader.TokenType != JsonTokenType.PropertyName) thrownew JsonException();
string propertyName = reader.GetString(); if (propertyName != "ProductType") thrownew JsonException();
if (reader.TokenType != JsonTokenType.Number) thrownew JsonException();
Extract the discriminator from the reader and create a response object based on it.
1 2 3 4 5 6 7
var discriminator = (ProductTypeDiscriminator)reader.GetInt32(); Person person = typeDiscriminator switch { TypeDiscriminator.Customer => new Customer(), TypeDiscriminator.Employee => new Employee(), _ => thrownew JsonException() };
Itterate over the reader and set each property value manually.
An alternative could be to read the json object before progressing the reader and then deserializing it.
needs a copy of the reader as copiedReader (its a struct so will be a copy on the heap)
the reader needs to be completed else it will shout, a hack is to have while (reader.Read()) and then a condition to check for if (reader.TokenType == JsonTokenType.EndObject)
1 2
var jsonObject = JsonDocument.ParseValue(ref copiedReader).RootElement.GetRawText(); var myDto = (MyDto) JsonSerializer.Deserialize(jsonObject, myDtoType, DeserializerOptions.Default);
Register
1 2 3 4 5
var serializeOptions = new JsonSerializerOptions();