The scenario is the following: I have some classes part of an sdk and in a type hierarchy, I cannot don’t want to mess around with them. I also have a json returned from a service.
The issue (and I considered it actually a bug in the service, but this is out of my control) is that some properties in the json are returned as an object while the property in the class is defined as a string. So for example
class MyClass {
string? Foo { get; set; }
string? Bar { get; set; }
}
But the json looks like:
{
"Foo": "{"SomeProperty": 123 }",
"Bar": {
"SomeProperty": 456
}
}
The property Foo is correct and give no issue, Bar on the other hand is not correct.
When deserializing the json
var jsonObject = JObject.Load(reader);
var obj = jsonObject.ToObject<MyClass>();
this fails with the error: Error reading string. Unexpected token: StartObject.
And while I totally agree with the error, I would like to make this work. Bar should just contain the serialised object (string).
To be clear: I don’t want a custom serialisation for MyClass. I am looking for some kind of custom convertor that can handle the mismatch for any property defined as a string but encountered as an object.
3
Answers
Conver all expressions to string first then deserialize them to the corresponding object.
Create Class to the corresponding expression.
Add it in MyClass
After deserializing to MyClass, deserialize the property Foo to the property RealFoo
Example:
Output => 123
Note: it’s not the best solution but it’s a work around to deal with the bug in the service you use
Create additional DTO class:
Load firstly to DTO, then convert
Bar
object to string.After that create
MyClass
instance from DTO.Is this solution acceptable to you?
Here is a quick implementation for such a StringConverter.
How to use