I have simple class:
public class TestObject {
public string Label { get; set; } = string.Empty;
public double Number { get; set; } = 0;
}
I would like to get an instance of TestObject from json. The trick is to allow Label and Number properties be optional, but throw exception if any extra field are added (to avoid mistake like "Lebel").
Code below alway convert to TestObject:
var correctInput = $"{{\"Label\":\"a\", \"Number\":5 }}";
var incorrectInput = $"{{\"Labell\":\"a\", \"Numberr\":5 }}";
JToken obj1 = JsonConvert.DeserializeObject<dynamic>(correctInput);
JToken obj2 = JsonConvert.DeserializeObject<dynamic>(incorrectInput);
var correctResult = obj1.ToObject<TestObject>();
var incorrectResult = obj2.ToObject<TestObject>();
Console.WriteLine($"Label: {correctResult.Label} Number: {correctResult.Number}");
Console.WriteLine($"Label: {incorrectResult.Label} Number: {incorrectResult.Number}");
The output of it will be:
Label: a Number: 5
Label: Number: 0
Only solution which comes to my mind is to define extra field with property [JsonExtensionData] and throw exception to set accessor:
[JsonExtensionData]
private IDictionary<string, JToken> _extraStuff {
get { return _extraStuff1; }
set { throw new Exception("cannot do it");}
}
But it is quite ugly hack.