I use property setters to validate the input in a C# class and throw Exceptions on invalid inputs. I also use Json.NET to deserialize a json to an object. The problem is that I don't know where to catch the exceptions for invalid json values which are thrown by the setters.
The Exception are not thrown from JsonConvert.DeserializeObject
method.
public class A{
private string a;
public string number{
get {return a;}
set {
if (!Regex.IsMatch(value, "^\\d+$"))
throw new Exception();
a = value;
}
}
}
public class Main
{
public static void main()
{
// The Exception cannot be caught here.
A a = JsonConvert.DeserializeObject<A>("{number:'some thing'}");
}
}
Serialization or deserialization errors will typically result in a JsonSerializationException .
In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom . Net object. In the following code, it creates a JavaScriptSerializer instance and calls Deserialize() by passing JSON data. It returns a custom object (BlogSites) from JSON data.
Deserializes the JSON to the specified . NET type. Deserializes the JSON to the specified . NET type using a collection of JsonConverter.
A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.
You need to subscribe to errors while deserializing your object:
JsonConvert.DeserializeObject<A>("{number:'some thing'}",
new JsonSerializerSettings
{
Error = (sender, args) =>
{
Console.WriteLine(args.ErrorContext.Error.Message);
args.ErrorContext.Handled = true;
}
});
If you remove args.ErrorContext.Handled = true
statement, exception raised in your setter will be rethrown from JsonConvert.DeserializeObject
method. It will be wrapped in JsonSerializationException
(" Error setting value to 'number' ").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With