I have a code that takes messages of any type and serialize them into the DB, while saving the type of the message and the serialized json string. I have a side process that should deserialize the messages later on and send them to the queue.
To perform the serialization and deserialization I use JsonConvert
of Newtonsoft.Json:
- For deserialization I use the following method:
object? DeserializeObject(string value, Type type)
- For serialization I use the following method:
string SerializeObject(object? value)
I have the following questions:
A. I saw that in case DeserializeObject
receives a wrong type name it still deserialize the object but his type is Newtonsoft.Json.Linq.JObject
and not the type I passed into the method, I expected it will throw an exception, this behavior is very bad for us, is there any way to cause the deserialize to throw exception in this scenario?
B. Is the code below secured? I saw that the library has variabilities such as depicted here
private void StackOverflowQuestion()
{
Bus.Employees.Messages.LevelCreated levelCreated = new Bus.Employees.Messages.LevelCreated
{
Name = "director",
};
//var messageType = levelCreated.GetType().AssemblyQualifiedName;
string messageData = JsonConvert.SerializeObject(levelCreated);
//Deserialize with type that is not correct
object deserializeMessaged = DeserializeMessage("my cool type which does not exists!", messageData);
string theType = deserializeMessaged.GetType().FullName;//theType = Newtonsoft.Json.Linq.JObject
}
private object DeserializeMessage(string messageType, string messageSerializedData)
{
Type type = Type.GetType(messageType);
return JsonConvert.DeserializeObject(value: messageSerializedData, type);
}