I have a contract whose json may or may not be in correct shape. The contract is this:
class TestContract
{
string TestString1;
string TestString2;
}
The json usually looks like this:
{ "TestString1": "Test", "TestString2": "Test" }
But it could look like this:
{ "TestString1": "Test", "TestString2":{ "Field": "Test" } }
The second case means something has gone wrong, but I do not want to throw an exception. I want to log that there is an issue, ignore TestString2 and proceed with the serialization.
In this case the resulting object should be the same as the one from this json string:
{ "TestString1": "Test" }
However, this seemingly cannot be handled with regular error handling (https://www.newtonsoft.com/json/help/html/SerializationErrorHandling.htm), because the error propagates up and the entire resulting object is null.
I don't see a reason why this shouldn't be able to be done, because the json is valid, just represents a slightly different object than the one I am deserializing into, just the same way as if you handle the error of trying to cast a string into an int. But I can't find any way to handle this. I saw a suggestion for using JsonReader, but it doesn't seem this can work as a generic solution. I need the error handling to take place no matter how complex the class and object are.
Anyone ever tried this before?