Example usage for com.fasterxml.jackson.databind ObjectMapper registerModule

List of usage examples for com.fasterxml.jackson.databind ObjectMapper registerModule

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper registerModule.

Prototype

public ObjectMapper registerModule(Module module) 

Source Link

Document

Method for registering a module that can extend functionality provided by this mapper; for example, by adding providers for custom serializers and deserializers.

Usage

From source file:org.lable.rfc3881.auditlogger.serialization.ReferenceableSerializerTest.java

@Test
public void nullFieldAllowEmptyTest() throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    objectMapper.registerModule(new ReferenceableSerializerModule());

    CodeReference codeReference = new CodeReference("CS", "", "001", "One");

    String result = objectMapper.writeValueAsString(codeReference);

    assertThat(result,/*from  w  w w . ja  v  a 2s .co  m*/
            is("{" + "\"cs\":\"CS\"," + "\"code\":\"001\"," + "\"csn\":\"\"," + "\"dn\":\"One\"" + "}"));
}

From source file:org.springframework.social.gitlab.api.core.impl.GitlabTemplate.java

@Override
protected MappingJackson2HttpMessageConverter getJsonMessageConverter() {
    MappingJackson2HttpMessageConverter converter = super.getJsonMessageConverter();
    ObjectMapper objectMapper = converter.getObjectMapper();
    objectMapper.registerModule(new GitlabModule());

    return converter;
}

From source file:org.springframework.social.twitter.api.impl.TweetDeserializer.java

private ObjectMapper createMapper() {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new TwitterModule());
    return mapper;
}

From source file:edu.ucsd.crbs.cws.dao.rest.WorkflowRestDAOImpl.java

@Override
public Workflow resave(long workflowId) throws Exception {
    ClientConfig cc = new DefaultClientConfig();
    cc.getClasses().add(StringProvider.class);
    Client client = Client.create(cc);//from w  w w .  j  a  va 2 s  .c o m
    client.addFilter(new HTTPBasicAuthFilter(_user.getLogin(), _user.getToken()));
    client.setFollowRedirects(true);
    WebResource resource = client.resource(_restURL).path(Constants.REST_PATH).path(Constants.WORKFLOWS_PATH)
            .path(Long.toString(workflowId));

    MultivaluedMap queryParams = _multivaluedMapFactory.getMultivaluedMap(_user);

    queryParams.add(Constants.RESAVE_QUERY_PARAM, Boolean.TRUE.toString());

    String json = resource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON)
            .type(MediaType.APPLICATION_JSON_TYPE).entity("{}").post(String.class);

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new ObjectifyJacksonModule());
    return mapper.readValue(json, new TypeReference<Workflow>() {
    });
}

From source file:edu.ucsd.crbs.cws.dao.rest.WorkflowRestDAOImpl.java

@Override
public List<Workflow> getAllWorkflows(boolean omitWorkflowParams, final Boolean showDeleted) throws Exception {
    ClientConfig cc = new DefaultClientConfig();
    cc.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
    Client client = Client.create(cc);/*from  www.j  a v a 2 s.  c om*/
    client.addFilter(new HTTPBasicAuthFilter(_user.getLogin(), _user.getToken()));
    client.setFollowRedirects(true);
    WebResource resource = client.resource(_restURL).path(Constants.REST_PATH).path(Constants.WORKFLOWS_PATH);
    MultivaluedMap queryParams = _multivaluedMapFactory.getMultivaluedMap(_user);

    if (omitWorkflowParams == true) {
        queryParams.add(Constants.NOWORKFLOWPARAMS_QUERY_PARAM, Boolean.TRUE.toString());
    }

    if (showDeleted != null) {
        queryParams.add(Constants.SHOW_DELETED_QUERY_PARAM, showDeleted.toString());
    }

    String json = resource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON).get(String.class);
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new ObjectifyJacksonModule());
    return mapper.readValue(json, new TypeReference<List<Workflow>>() {
    });
}

From source file:com.epam.ta.reportportal.core.configs.JacksonConfiguration.java

/**
 * /*  www. ja  va2s  .c o  m*/
 * 
 * @return
 */
@Bean(name = "objectMapper")
public ObjectMapper objectMapper() {
    ObjectMapper om = new ObjectMapper();
    om.setAnnotationIntrospector(new JacksonAnnotationIntrospector());
    om.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);
    om.registerModule(new JacksonViewAwareModule(om));
    return om;
}

From source file:com.strandls.alchemy.webservices.common.json.ExceptionObjectMapperModule.java

/**
 * Binding for throwable exception mapper.
 *
 * @param mapper/*from w  ww  . jav  a  2 s.c o  m*/
 * @return
 */
@Provides
@Singleton
@ThrowableObjectMapper
@Inject
public ObjectMapper getExceptionObjectMapper(final ObjectMapper mapper,
        final RestInterfaceAnalyzer restInterfaceAnalyzer, final JavaTypeQueryHandler typeQueryHandler) {
    // can't copy owing to bug -
    // https://github.com/FasterXML/jackson-databind/issues/245
    final ObjectMapper exceptionMapper = mapper;
    exceptionMapper.registerModule(new SimpleModule() {
        /**
         * The serial version id.
         */
        private static final long serialVersionUID = 1L;

        /*
         * (non-Javadoc)
         * @see
         * com.fasterxml.jackson.databind.module.SimpleModule#setupModule
         * (com.fasterxml.jackson.databind.Module.SetupContext)
         */
        @Override
        public void setupModule(final SetupContext context) {
            // find exceptions thrown by webservices
            final Set<Class<?>> serviceClasses = typeQueryHandler.getTypesAnnotatedWith(ALCHEMY_SERVICE_PACKAGE,
                    Path.class);
            final Set<Class<?>> exceptionsUsed = new HashSet<Class<?>>();
            for (final Class<?> serviceClass : serviceClasses) {
                // get hold of all rest methods and hence exception
                try {
                    final Set<Method> restMethods = restInterfaceAnalyzer.analyze(serviceClass)
                            .getMethodMetaData().keySet();
                    for (final Method method : restMethods) {
                        for (final Class<?> exceptionClass : method.getExceptionTypes()) {
                            exceptionsUsed.add(exceptionClass);
                        }
                    }
                } catch (final NotRestInterfaceException e) {
                    log.error("Error geting exception classes for methods from {}", serviceClass);
                    throw new RuntimeException(e);
                }
            }

            // add the mixin to all jaxrs classes as well.
            exceptionsUsed
                    .addAll(typeQueryHandler.getSubTypesOf(JAVAX_WS_RS_PACKAGE, WebApplicationException.class));

            for (final Class<?> exceptionClass : exceptionsUsed) {
                // add a mixin to prevent server stack trace from showing up
                // to the client.
                log.debug("Applied mixin mask to {}", exceptionClass);
                context.setMixInAnnotations(exceptionClass, ThrowableMaskMixin.class);
            }

        }
    });
    exceptionMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return exceptionMapper;
}

From source file:org.mayocat.rest.jackson.DateTimeISO8601SerializerTest.java

private final ObjectMapper jodaMapper() {
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule testModule = new SimpleModule("MyModule", new Version(1, 0, 0, null));
    testModule.addSerializer(new DateTimeISO8601Serializer());
    mapper.registerModule(testModule);
    return mapper;
}

From source file:com.miserablemind.api.consumer.tradeking.api.impl.response_entities.TKUserResponse.java

/**
 * For User Profile TradeKing returns an array instead of some sensible normal object
 * The getter methods get it from the List that is turned into hash map for faster access.
 *
 * @param userData data fed in my deserializer
 * @throws Exception if cannot deserialize data
 *//*ww  w  .jav a 2s  .  c o m*/
@SuppressWarnings("unchecked")
@JsonSetter("userdata")
public void deserializeUserData(LinkedHashMap<String, Object> userData) throws Exception {

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new TradeKingModule());

    boolean isDisabled = userData.get("disabled").equals("true");
    boolean resetPassword = userData.get("resetpassword").equals("true");
    boolean resetTradingPassword = userData.get("resettradingpassword").equals("true");

    UserAccount[] accounts = (UserAccount[]) this.extractArray(UserAccount[].class, userData, "account");

    //User Profile Object
    UserProfile userProfile = new UserProfile();

    LinkedHashMap<String, ArrayList> data = (LinkedHashMap<String, ArrayList>) userData.get("userprofile");
    ArrayList<LinkedHashMap<String, String>> entry = (ArrayList<LinkedHashMap<String, String>>) data
            .get("entry");

    for (LinkedHashMap<String, String> entryLine : entry) {
        UserProfileKeys key = UserProfileKeys.fromString(entryLine.get("name"));

        //catch all
        if (null == key) {
            userProfile.add(entryLine.get("name"), entryLine.get("value"));
            continue;
        }

        switch (key) {
        case AGREEMENT_FDIC:
            userProfile.setFDICAgreement(entryLine.get("value"));
            break;
        case DASHBOARD_COLLAPSED:
            userProfile.setAccountSummaryDashboardCollapsed(entryLine.get("value"));
            break;
        case EMAIL_ADDRESS:
            userProfile.setEmailAddress(entryLine.get("value"));
            break;
        case UUID:
            userProfile.setUUID(entryLine.get("value"));
            break;
        case FDIC_PAPER:
            userProfile.setFDICPaper(entryLine.get("value"));
            break;
        case FIRST_NAME:
            userProfile.setFirstName(entryLine.get("value"));
            break;
        case GAINS_KEEPER:
            userProfile.setGainsKeeper(entryLine.get("value").equals("Y"));
            break;
        case LAST_NAME:
            userProfile.setLasName(entryLine.get("value"));
            break;
        case NEW_MESSAGE:
            userProfile.setHasMewMessage(entryLine.get("value").equals("Y"));
            break;
        case REAL_TIME_STOCK_QUOTE:
            userProfile.setRealTimeStockQuote(entryLine.get("value").equals("Y"));
            break;
        case USE_TRADING_PASSWORD:
            userProfile.setTradingPasswordUsed(entryLine.get("value").equals("Y"));
            break;
        default:
            userProfile.add(entryLine.get("name"), entryLine.get("value"));
        }
    }

    this.user = new TradeKingUser(isDisabled, resetPassword, resetTradingPassword, accounts, userProfile);

}

From source file:com.wealdtech.jackson.ObjectMapperFactory.java

/**
 * Build an objectmapper from a given configuration.
 *
 * @param configuration/*from w w w  .  j  a  v a 2 s.  c om*/
 *          the objectmapper configuration
 * @return an objectmapper
 */
public ObjectMapper build(final ObjectMapperConfiguration configuration) {
    final ObjectMapper mapper = new ObjectMapper(configuration.getFactory().orNull());
    for (Module module : configuration.getModules()) {
        mapper.registerModule(module);
    }
    for (Map.Entry<JsonParser.Feature, Boolean> entry : configuration.getParserFeatures().entrySet()) {
        mapper.getFactory().configure(entry.getKey(), entry.getValue());
    }
    mapper.setInjectableValues(configuration.getInjectableValues());
    if (configuration.getPropertyNamingStrategy().isPresent()) {
        mapper.setPropertyNamingStrategy(configuration.getPropertyNamingStrategy().get());
    }
    if (configuration.getSerializationInclusion().isPresent()) {
        mapper.setSerializationInclusion(configuration.getSerializationInclusion().get());
    }

    return mapper;
}