Why does writeObject throw java.io.NotSerializableException and how do I fix it?
java.io.NotSerializableException
can occur when you serialize an inner class instance because:
serializing such an inner class instance will result in serialization of its associated outer class instance as well
Serialization of inner classes (i.e., nested classes that are not static member classes), including local and anonymous classes, is strongly discouraged
Ref: The Serializable Interface
The fields of your object have in turn their fields, some of which do not implement Serializable
. In your case the offending class is TransformGroup
. How to solve it?
- if the class is yours, make it
Serializable
- if the class is 3rd party, but you don't need it in the serialized form, mark the field as
transient
- if you need its data and it's third party, consider other means of serialization, like JSON, XML, BSON, MessagePack, etc. where you can get 3rd party objects serialized without modifying their definitions.
Make the class serializable by implementing the interface java.io.Serializable
.
java.io.Serializable
- Marker Interface which does not have any methods in it.- Purpose of Marker Interface - to tell the
ObjectOutputStream
that this object is a serializable object.
As mentioned above if the class is a 3rd party class you need to convert it to a JSON/XML/BSON object as the 3rd party class object cannot be serialized.
I was working on my project and had the same issue and i used gson library to convert my class object to a JSON String. Afterwhich i used this String in that object and passed it through ObjectOutputStream object. And over the client side i used the same to revert the JSON String back to the 3rd party class object.
You can download the jar from over here : https://jar-download.com/artifacts/com.google.code.gson/gson/2.8.2/source-code!
Here's how i did it :
// Method that returns String through a Object as a parameter i.e to be converted
public static String generateJSONStringFromObject(ThirdPartyClass object) throws JsonProcessingException{
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
String jsonString = mapper.writeValueAsString(object);
return jsonString;
}
// Method that returns Object through a String as a parameter
public static ThirdPartyClass generateObjectFromJSONString(String jsonString){
Gson gson = new Gson();
ThirdPartyClass thirdPartyClassObject = gson.fromJson(jsonString, ThirdPartyClass.class);
return thirdPartyClassObject;
}