we are saving the data after serializing for a particular column, so while retrieving the data and before deserializing how to check if the string is deserializable ??
Ensuring that a string represents a valid serialized object is nearly as hard as performing deserialization itself, because you would need to walk the serialized object graph, figuring out where each serialized field starts, and what would be the data that goes into that field.
The only operations that you could save are the allocations of the object and its dependents. These operations are certainly not free, but they are highly optimized, so your savings are not going to be overly significant.
Instead of pre-validating the string before deserialization, you could take a speculative approach, and assume that your deserialization will succeed. Your code could jump right into deserializing your string, and in most cases it will succeed!* To ensure that your code does not break when the string is invalid, wrap deserialization calls into a try/catch
, and watch for deserialization exceptions. If you catch any of them, you know that the string was invalid; if you do not catch deserialization exceptions, you would know that the string is valid, and you would also have your deserialized object ready for use.
Assuming XML serialization, your code could do something like this:
static bool TryDeserialize<T>(string xmlStr, out T obj) {
var ser = new XmlSerializer(typeof(T));
using(var stringReader = new StringReader(xmlStr)) {
using (var xmlReader = new XmlTextReader(stringReader)) {
try {
obj = ser.Deserialize(xmlReader);
} catch {
obj = default(T);
return false;
}
}
}
return true;
}
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