How to serialize transient fields using jackson?

后端 未结 3 2012
不知归路
不知归路 2021-01-02 16:09

We use JSON serialization with Jackson to expose internal state of the system for debugging properties.

By default jackson does not serialize transient fields - but

相关标签:
3条回答
  • 2021-01-02 16:23

    My solution with Jackson 2.4.3:

      private static final ObjectMapper mapper =
            new ObjectMapper(){{
    
                Hibernate4Module module = new Hibernate4Module();
                module.disable(Hibernate4Module.Feature.USE_TRANSIENT_ANNOTATION);
                registerModule(module);
    
            }};
    
    0 讨论(0)
  • 2021-01-02 16:23

    You can create a custom getter for that transient field and use @XmlElement attribute. It doesn´t matter the name of that getter.

    For example:

    public class Person {
    
         @XmlTransient private String lastname;
    
         @XmlElement(name="lastname")
         public String getAnyNameOfMethod(){
             return lastname;
         }
    
    }
    
    0 讨论(0)
  • 2021-01-02 16:45

    I don't think Jackson supports any type of configuration to enable it to serialize a transient field. There's an open issue to add that feature, but it's old and hasn't been addressed (as far as I can tell): http://jira.codehaus.org/browse/JACKSON-623

    So my question is: Is there a way to setup jackson to serialize all the objects fields? include transient ones.

    So to answer your question, no.

    Some other Java JSON tools, such as GSON do support a configuration option to serialize transient fields. If you can use another tool, you might look into that (for GSON, see: https://sites.google.com/site/gson/gson-user-guide).

    To expand a little, you might try a different approach.

    First, You shouldn't try to serialize a transient field. After all the definition of transient is "don't serialize this." Nevertheless I can think of a few specific situations where it might be necessary, or at least convenient (like when working with code you can't modify or such). Still, in 99% of cases, the answer is don't do that. Change the field so that it's not transient if you need to serialize it. If you have multiple contexts where you use the same field, and you want it serialized in one (JSON, for example), and not serialized in another (java.io, for example) then you should create a custom serializer for the case where you don't want it, rather than abuse the keyword.

    Second, as to using a getter and having "some getters that change the objects state," you should try to avoid that too. That can lead to various unintended consequences. And, technically, that's not a getter, that's a setter. What I mean is, if it mutates state, you've got a mutator (setter) rather than accessor (getter), even if you name it following the "get" convention and return some stuff.

    0 讨论(0)
提交回复
热议问题