Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a field non-serializable in java?

Tags:

java

Please, I need help with serializing data.

I have a class called Foo which defines 3 attributes:

    public int age;     public String name;     public String description; 

How can I serialize this object, but without its description field?

Thanks in advance!

like image 601
Mirel Vlad Avatar asked Dec 03 '12 16:12

Mirel Vlad


People also ask

How do you not serialize a field in Java?

If there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.

How do you make an object non-serializable in Java?

You can't serialise a class that doesn't implement Serializable , but you can wrap it in a class that does. To do this, you should implement readObject and writeObject on your wrapper class so you can serialise its objects in a custom way. First, make your non-serialisable field transient .

How do you make a class non-serializable in Java?

There is no direct way to prevent sub-class from serialization in java. One possible way by which a programmer can achieve this is by implementing the writeObject() and readObject() methods in the subclass and needs to throw NotSerializableException from these methods.

How can we prevent field serialization?

writeValueAsString(currentUser); This will prevent password field to get serialized. Also you will be able to deserialize password fields as it is. Just make sure no filters are applied on the ObjectMapper object.


1 Answers

Use keyword transient:

public transient String description; 
like image 139
bellum Avatar answered Sep 24 '22 08:09

bellum