I have the following serializable class (implements serializable):
public class Test implements Serializable{
private String id;
private Map<String,Object> otherProperties;
}
However , it seems like this property is causing some problems with serialization :
How can I solve this problem ?
Also , is there any downside in not making this transient or serializable ? Will I be able to serialize this class fully ?
In case you define any data member as transient, it will not be serialized. This is because every field marked as transient will not be serialized. You can use this transient keyword to indicate the Java virtual machine (JVM) that the transient variable is not part of the persistent state of an object.
By making a field Public It is one of the simplest ways by which we can make a field serialize and de-serialize. In this way, we simply make the field public for this. We will declare a class with a public, a protected and a private field. By default, only the available field will be serialized to JSON.
transient is a variables modifier used in serialization. At the time of serialization, if we don't want to save value of a particular variable in a file, then we use transient keyword. When JVM comes across transient keyword, it ignores original value of the variable and save default value of that variable data type.
A serializable class can declare its own serialVersionUID explicitly by declaring a field named “ serialVersionUID ” that must be static, final, and of type long.
The Map
interface does not extend the Serializable
interface, which is why Sonar is warning you.
When serializing an instance of Test
, you must choose whether or not you want otherProperties
to be serialized.
If you don't want to serialize otherProperties
, then the field should be marked as transient
:
private transient Map<String, Object> otherProperties;
Otherwise, you can change the type of otherProperties
to an implementation of Map
that implements Serializable
, such as HashMap
.
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