Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

java - Serialization and Deserialization with Jackson: how to programmatically ignore fields?

I'm using Jackson to serialize and deserialize objects. The problem is that sometimes I want to show a field and sometimes not.

Actually I'm using the @JsonIgnore to avoid the printing of the property when I don't need it. When I need it I'm disabling the Property through

mapper.getSerializationConfig().disable(SerializationConfig.Feature.USE_ANNOTATIONS);

but this will disable also other annotations that I need.

How can I get the result that I need? Using Views? Any example?

A little pojo to understand what I want:

class User {
private String username;
@JsonIgnore    
private String password;    
    // getter setter
}


writeToDB() {
mapper.getSerializationConfig().disable(SerializationConfig.Feature.USE_ANNOTATIONS);
mapper.writeValueAsString(user);
}

and through the REST API you can get the username without the password (thanks to the JsonIgnore)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In the end I've handled this in a different way. I was using Jersey and Guice so was a little hard to find out how, but I did it.

Basically I used the MixIn annotations of Jackson but using Jersey I had to create the ObjectMapper into a Provider and then bind it with Guice.

In this way when I'm using the REST service Jersey will use the ObjectMapper defined in the Provider; when storing the stuff Jackson will use the standard ObjectMapper.

Now some code.

create the PrivateUser class:

public abstract class PrivateUser {
  @JsonIgnore abstract String getPassword();
}

create the provider:

@Provider
public class JacksonMixInProvider implements ContextResolver<ObjectMapper> {

  @Override
  public ObjectMapper getContext(Class<?> aClass) {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.getSerializationConfig().addMixInAnnotations(User.class, PrivateUser.class);
    return mapper;
  }
}

and bind it:

bind(JacksonMixInProvider.class).asEagerSingleton();

That's it! :D

Hope this will help someone else to waste less time!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...