Home > Enterprise >  Conflicting types of serialization/deserialization and annotations
Conflicting types of serialization/deserialization and annotations

Time:01-30

I've just started to learn about serialization/deserialization and I'm a bit confused about which type is used where and when... let me explain:

I have an object containing many fields some of which are full of "useless" info. Now, when I log the contents of such object for debugging purposes I would like the output to be in a nice json format.

So in the toString() method of this object I do the following:

import com.fasterxml.jackson.databind.ObjectMapper;

    ...
    ...

    @Override
    public String toString() {
        ObjectMapper objectMapper = new ObjectMapper();
        String s = "";
        try{
            s = objectMapper.writeValueAsString(this);
        } catch (Exception e) {
            
        }
        return s;
    }

but this also logs all the useless fields.

So I've looked around and found the @JsonIgnore annotation from com.fasterxml.jackson.annotation.JsonIgnore which I can put on top of the useless fields so as not to log them.

But from what I've understood serialization is a process of transforming a java object into a bytestream so that it can be written to file, saved in session, sent across the internet. So my noob question is: is it possible that using the @JsonIgnore annotation on top of certain fields will result in those fields not being saved into session (I use an hazelcast map), or not being sent in the http responses I send, or not being written to a file If I ever decide to do that?

If the answer to the previous question is NO, then is that because those types of actions (saving in session, writing to file, sending as http response) use different types of serialization than objectMapper.writeValueAsString(this); so they don't conflict?

CodePudding user response:

In your case, you're using Jackson's ObjectMapper to convert your object to a string representation (in JSON format). The @JsonIgnore annotation is part of Jackson's annotations and will prevent fields annotated with it from being included in the JSON representation of your object.

However, this only affects the string representation created by the ObjectMapper, not other forms of serialization/deserialization. If you want to persist the object in a specific way, you may need to use a different form of serialization (such as binary serialization) or create a custom representation that excludes the fields you don't want to save.

So to answer your questions:

No, using @JsonIgnore will not affect the object saved in a session or sent as an HTTP response. Yes, that's correct. Different forms of serialization/deserialization may handle fields differently, even if they are part of the same object.

  • Related