JSON. Net supports Exception Handling During serialization and deserialization. Exception Handling allows you to capture an exception. You can choose whether to process it, continue serialization, or let the exception be thrown to the previous layer.ProgramIs thrown.
The error event on jsonserializer and onerrorattribute are defined in two ways.
> Error event
Error event is an exception handling task created on jsonserializer. when JSON is serialized or deserialized, an error event is triggered if any exception is thrown. just like all the settings created on jsonserializer, it can also be set on jsonserializersettings and passed to the serialization method of jsonconvert.
Example:
List <string> errors = new list <string> ();
List <datetime> C = jsonconvert. deserializeobject <list <datetime> (@"[
"" 2010-12-19t00: 00: 00Z "",
"" I am not a date and will error! "",
[
1
],
"" 2011-01-01t00: 00: 00Z "",
Null,
"" 2010-12-25t00: 00: 00Z ""
] ", New jsonserializersettings ()
{
Error = delegate (Object sender, newtonsoft. JSON. serialization. erroreventargs E)
{
Errors. Add (E. errorcontext. Error. Message );
E. errorcontext. Handled = true;
},
Converters = {New isodatetimeconverter ()}
});
Foreach (datetime t in C)
{
Console. writeline (T. tostring ());
}
// 2010-12-19 00:00:00
// 00:00:00
// 2010-12-25 00:00:00
Foreach (string err in errors)
{
Console. writeline (ERR );
}
// The string was not recognized as a valid datetime. There is a unknown word starting at index 0.
// Unexpected token parsing date. Expected string, got startarray.
// Cannot convert null value to system. datetime.
In this example, we deserialize a json array into a datetime set. In jsonserializersettings, A hander is assigned an error event to record the error message, mark the error as handled ).
The result of deserialization of JSON is three successful deserialization dates and three error messages: one is incorrect format, "I am not a date and will error! ", One is nested JSON array, and the last one is null value, because the defined list does not allow the datetime with an empty type. this event processing has recorded this information, JSON. net continues during serialization (not stopped due to exceptions) because these errors have been marked as handled.
It is worth noting that in JSON.. Net exception handling, the unhandled exception will be thrown to the previous layer, and each of its parent triggers the event, for example, when serializing a collection of several objects, an unprocessed exception will be triggered twice, first on the object and then on the set. In this way, you can choose where the exception occurs or a parent when handling the exception.
Jsonserializer serializer = new jsonserializer ();
Serializer. Error + = delegate (Object sender, newtonsoft. JSON. serialization. erroreventargs E)
{
// Only log an error once
If (E. currentobject = E. errorcontext. originalobject)
Errors. Add (E. errorcontext. Error. Message );
};
If you do not want to handle an exception immediately, but want to perform an operation on it, you can verify whether erroreventarg's currentobject is equal to originalobject. originalobject is the object that throws an exception, and currentobject is the object that the event is triggered. they will only be equal to the first time (when the event is triggered by originalobject.
> Onerrorattribute
Onerrorattribute works like other JSON.. net support. net serialization attributes. It can be used simply by marking it on a method with the correct parameters (A streamingcontext and an errorcontext). It has nothing to do with the method name.
Example:
Public class personerror
{
Private list <string> _ roles;
Public string name {Get; set ;}
Public int age {Get; set ;}
Public list <string> roles
{
Get
{
If (_ roles = NULL)
Throw new exception ("roles not loaded! ");
Return _ roles;
}
Set {_ roles = value ;}
}
Public String title {Get; set ;}
[Onerror]
Internal void onerror (streamingcontext context, errorcontext)
{
Errorcontext. Handled = true;
}
}
In this example, when _ roles is not set, an exception is thrown when the roles attribute is accessed. when serializing the roles attribute, the exception handling method sets error to handled to allow JSON. net continues to serialize this class.
Test:
Personerror person = new personerror
{
Name = "George Michael Bluth ",
Age = 16,
Roles = NULL,
Title = "Mister manager"
};
String JSON = jsonconvert. serializeobject (person, formatting. indented );
Console. writeline (JSON );
Output:
{< BR style =" padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-Right: 0px; padding-top: 0px ">" name ":" George Michael Bluth ",
" Age ": 16,
" title ":" Mister manager "
}