Java Code Examples for com.fasterxml.jackson.databind.ObjectMapper#registerModule()

The following examples show how to use com.fasterxml.jackson.databind.ObjectMapper#registerModule() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OpenSkyApi.java    From opensky-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Create an instance of the API for authenticated access
 * @param username an OpenSky username
 * @param password an OpenSky password for the given username
 */
public OpenSkyApi(String username, String password) {
	lastRequestTime = new HashMap<>();
	// set up JSON mapper
	mapper = new ObjectMapper();
	SimpleModule sm = new SimpleModule();
	sm.addDeserializer(OpenSkyStates.class, new OpenSkyStatesDeserializer());
	mapper.registerModule(sm);

	authenticated = username != null && password != null;

       if (authenticated) {
           okHttpClient = new OkHttpClient.Builder()
                   .addInterceptor(new BasicAuthInterceptor(username, password))
                   .build();
       } else {
           okHttpClient = new OkHttpClient();
       }
}
 
Example 2
Source File: AbstractBounceProxyServerTest.java    From joynr with Apache License 2.0 6 votes vote down vote up
private ObjectMapper getObjectMapper() {
    objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
    // objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS,
    // true);
    objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, true);
    objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    objectMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);

    objectMapper.enableDefaultTypingAsProperty(DefaultTyping.JAVA_LANG_OBJECT, "_typeName");
    TypeResolverBuilder<?> joynrTypeResolverBuilder = objectMapper.getSerializationConfig()
                                                                  .getDefaultTyper(SimpleType.construct(Object.class));

    SimpleModule module = new SimpleModule("NonTypedModule", new Version(1, 0, 0, "", "", ""));
    module.addSerializer(new JoynrEnumSerializer());
    module.addSerializer(new JoynrListSerializer());

    TypeDeserializer typeDeserializer = joynrTypeResolverBuilder.buildTypeDeserializer(objectMapper.getDeserializationConfig(),
                                                                                       SimpleType.construct(Object.class),
                                                                                       null);

    module.addDeserializer(Object.class, new JoynrUntypedObjectDeserializer(typeDeserializer));
    objectMapper.registerModule(module);
    return objectMapper;
}
 
Example 3
Source File: SwaggerReader.java    From netty-rest with Apache License 2.0 6 votes vote down vote up
public SwaggerReader(Swagger swagger, ObjectMapper mapper, BiConsumer<Method, Operation> swaggerOperationConsumer, Map<Class, PrimitiveType> externalTypes)
{
    this.swagger = swagger;
    modelConverters = new ModelConverters(mapper);
    this.swaggerOperationConsumer = swaggerOperationConsumer;
    modelConverters.addConverter(new ModelResolver(mapper));
    if (externalTypes != null) {
        setExternalTypes(externalTypes);
    }
    mapper.registerModule(
            new SimpleModule("swagger", Version.unknownVersion()) {
                @Override
                public void setupModule(SetupContext context) {
                    context.insertAnnotationIntrospector(new SwaggerJacksonAnnotationIntrospector());
                }
            });
    errorProperty = modelConverters.readAsProperty(HttpServer.ErrorMessage.class);
    swagger.addDefinition("ErrorMessage", modelConverters.read(HttpServer.ErrorMessage.class).entrySet().iterator().next().getValue());
}
 
Example 4
Source File: DefaultMigrationClient.java    From elasticsearch-migration with Apache License 2.0 6 votes vote down vote up
private ObjectMapper createObjectMapper() {
    final ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);
    objectMapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true);
    objectMapper.configure(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS, true);
    objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    objectMapper.registerModule(new Jdk8Module());
    objectMapper.registerModule(new JavaTimeModule());

    return objectMapper;
}
 
Example 5
Source File: ResourceProducer.java    From gazpachoquest with GNU General Public License v3.0 5 votes vote down vote up
@Produces
@GazpachoResource
@RequestScoped
public QuestionnaireResource createQuestionnairResource(HttpServletRequest request) {
    RespondentAccount principal = (RespondentAccount) request.getUserPrincipal();
    String apiKey = principal.getApiKey();
    String secret = principal.getSecret();

    logger.info("Getting QuestionnaireResource using api key {}/{} ", apiKey, secret);

    JacksonJsonProvider jacksonProvider = new JacksonJsonProvider();
    ObjectMapper mapper = new ObjectMapper();
    // mapper.findAndRegisterModules();
    mapper.registerModule(new JSR310Module());
    mapper.setSerializationInclusion(Include.NON_EMPTY);
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

    jacksonProvider.setMapper(mapper);

    QuestionnaireResource resource = JAXRSClientFactory.create(BASE_URI, QuestionnaireResource.class,
            Collections.singletonList(jacksonProvider), null);
    // proxies
    // WebClient.client(resource).header("Authorization", "GZQ " + apiKey);

    Client client = WebClient.client(resource);
    ClientConfiguration config = WebClient.getConfig(client);
    config.getOutInterceptors().add(new HmacAuthInterceptor(apiKey, secret));
    return resource;
}
 
Example 6
Source File: KafkaConsumerOffsetFetcher.java    From eagle with Apache License 2.0 5 votes vote down vote up
public KafkaConsumerOffsetFetcher(ZKConfig config, String... parameters) {
    try {
        this.curator = CuratorFrameworkFactory.newClient(config.zkQuorum, config.zkSessionTimeoutMs, 15000,
            new RetryNTimes(config.zkRetryTimes, config.zkRetryInterval));
        curator.start();
        this.zkRoot = config.zkRoot;
        mapper = new ObjectMapper();
        Module module = new SimpleModule("offset").registerSubtypes(new NamedType(KafkaConsumerOffset.class));
        mapper.registerModule(module);
        zkPathToPartition = String.format(config.zkRoot, parameters);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 7
Source File: StackTraceElementXmlMixInTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testFromJsonWithSimpleModule() throws Exception {
    final ObjectMapper mapper = new ObjectMapper();
    final SimpleModule module = new SimpleModule();
    module.addDeserializer(StackTraceElement.class, new Log4jStackTraceElementDeserializer());
    mapper.registerModule(module);
    final StackTraceElement expected = new StackTraceElement("package.SomeClass", "someMethod", "SomeClass.java",
            123);
    final String s = this
            .aposToQuotes("{'class':'package.SomeClass','method':'someMethod','file':'SomeClass.java','line':123}");
    final StackTraceElement actual = mapper.readValue(s, StackTraceElement.class);
    Assert.assertEquals(expected, actual);
}
 
Example 8
Source File: JobsConfiguration.java    From zuihou-admin-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * json 类型参数 序列化问题
 * Long -> string
 * date -> string
 *
 * @param builder
 * @return
 */
@Bean
@Primary
@ConditionalOnMissingBean
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
    ObjectMapper objectMapper = builder.createXmlMapper(false)
            .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .timeZone(TimeZone.getTimeZone("Asia/Shanghai"))
            .build();
    //忽略未知字段
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    //日期格式
    SimpleDateFormat outputFormat = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
    objectMapper.setDateFormat(outputFormat);
    SimpleModule simpleModule = new SimpleModule();
    /**
     *  将Long,BigInteger序列化的时候,转化为String
     */
    simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
    simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
    simpleModule.addSerializer(BigInteger.class, ToStringSerializer.instance);
    simpleModule.addSerializer(BigDecimal.class, ToStringSerializer.instance);

    objectMapper.registerModule(simpleModule);

    return objectMapper;
}
 
Example 9
Source File: DataExportCommand.java    From Cardshifter with Apache License 2.0 5 votes vote down vote up
private static ObjectMapper createMapper() {
    ObjectMapper mapper = CardshifterIO.mapper();
    SimpleModule module = new SimpleModule("ECSModule", new Version(0, 1, 0, "alpha", "com.cardshifter", "cardshifter"));
    module.addSerializer(Entity.class, new EntitySerializer());
    mapper.registerModule(module);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    return mapper;
}
 
Example 10
Source File: FooDeserializer.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
static Foo read(InputStream stream) throws IOException {
    ObjectMapper mapper = JsonUtil.createObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addDeserializer(Foo.class, new FooDeserializer());
    mapper.registerModule(module);
    return mapper.readValue(stream, Foo.class);
}
 
Example 11
Source File: NewRelicClient.java    From newrelic-alerts-configurator with Apache License 2.0 5 votes vote down vote up
private JacksonJsonProvider createMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
    mapper.setSerializationInclusion(NON_NULL);
    mapper.registerModule(new Jdk8Module());
    mapper.registerModule(new JavaTimeModule());
    return new JacksonJaxbJsonProvider(mapper, DEFAULT_ANNOTATIONS);
}
 
Example 12
Source File: JsonUtilities.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
public static ObjectMapper getObjectMapper(TimeZone timezone, String dateFormatPattern) {
	ObjectMapper mapper = new ObjectMapper();

	mapper.setTimeZone(timezone);
	mapper.setDateFormat(DateUtilities.getFormat(dateFormatPattern, timezone));
	mapper.registerModule(new LocalDateTimeModule());
	mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

	return mapper;
}
 
Example 13
Source File: ObjectMapperFactory.java    From web3j with Apache License 2.0 5 votes vote down vote up
private static ObjectMapper configureObjectMapper(
        ObjectMapper objectMapper, boolean shouldIncludeRawResponses) {
    if (shouldIncludeRawResponses) {
        SimpleModule module = new SimpleModule();
        module.setDeserializerModifier(
                new BeanDeserializerModifier() {
                    @Override
                    public JsonDeserializer<?> modifyDeserializer(
                            DeserializationConfig config,
                            BeanDescription beanDesc,
                            JsonDeserializer<?> deserializer) {
                        if (Response.class.isAssignableFrom(beanDesc.getBeanClass())) {
                            return new RawResponseDeserializer(deserializer);
                        }

                        return deserializer;
                    }
                });

        objectMapper.registerModule(module);
    }

    objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    return objectMapper;
}
 
Example 14
Source File: MyParkAPI.java    From springboot-seed with MIT License 5 votes vote down vote up
@ApiOperation(value = "最近一次停车记录")
@GetMapping(value = "/last_car_fee", produces = "application/json; charset=utf-8")
public ResponseEntity<?> car_fee_list() throws Exception {
    OAuth2Authentication auth = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
    Long currentUserId = ((SecurityUser) auth.getPrincipal()).getId();
    List<Car> carList = carService.selectAll(
            new QueryParameter[]{new QueryParameter("userId", QueryParameterMethod.EQUAL, currentUserId.toString(), QueryParameterType.LONG)});
    String cars = EMPTY_STRING;
    for (int i = 0; i < carList.size(); i++) {
        cars += carList.get(i).getCarNumber();
        if (i != carList.size() - 1)
            cars += ",";
    }
    QueryParameter[] parameters = new QueryParameter[]{
            new QueryParameter("carNumber", QueryParameterMethod.IN, cars, QueryParameterType.ARRAY),
            new QueryParameter("userId", QueryParameterMethod.IS_NULL, EMPTY_STRING, QueryParameterType.STRING)};
    List<CarFee> carFeeList = carFeeService.selectTop(1, parameters);
    if (carFeeList.size() != 1) {
        parameters = new QueryParameter[]{
                new QueryParameter("userId", QueryParameterMethod.EQUAL, currentUserId.toString(), QueryParameterType.LONG)
        };
        carFeeList = carFeeService.selectTop(1, parameters);
    }
    if (carFeeList.size() == 1) {
        Park park = parkService.selectByID(carFeeList.get(0).getParkId()).get();
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        SimpleModule module = new SimpleModule();
        module.addSerializer(String.class, new StringUnicodeSerializer());
        mapper.registerModule(module);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return ResponseEntity.status(HttpStatus.OK).header("park", mapper.writeValueAsString(park)).body(carFeeList.get(0));
    } else {
        return ResponseEntity.ok().build();
    }
}
 
Example 15
Source File: StackTraceElementJsonMixInTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testFromJsonWithLog4jModule() throws Exception {
    final ObjectMapper mapper = new ObjectMapper();
    final boolean encodeThreadContextAsList = false;
    final SimpleModule module = new Log4jJsonModule(encodeThreadContextAsList, true, false, false);
    module.addDeserializer(StackTraceElement.class, new Log4jStackTraceElementDeserializer());
    mapper.registerModule(module);
    final StackTraceElement expected = new StackTraceElement("package.SomeClass", "someMethod", "SomeClass.java", 123);
    final String s = this.aposToQuotes("{'class':'package.SomeClass','method':'someMethod','file':'SomeClass.java','line':123}");
    final StackTraceElement actual = mapper.readValue(s, StackTraceElement.class);
    Assert.assertEquals(expected, actual);
}
 
Example 16
Source File: EthJsonModuleTest.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
@Test
void testSerialize() throws Exception {
  BlockHeader header = BlockHeaderTest.generateBlockHeader();
  ObjectMapper mapper = new ObjectMapper();
  mapper.registerModule(new EthJsonModule());
  mapper.writer().writeValueAsString(header);
}
 
Example 17
Source File: BaragonService.java    From Baragon with Apache License 2.0 5 votes vote down vote up
public Module getObjectMapperModule() {
  return (binder) -> {
    final ObjectMapper objectMapper = new ObjectMapper();

    objectMapper.registerModule(new GuavaModule());
    objectMapper.registerModule(new Jdk8Module());

    binder.bind(ObjectMapper.class).toInstance(objectMapper);
  };
}
 
Example 18
Source File: JSONSerializable.java    From hazelcast-jet-demos with Apache License 2.0 5 votes vote down vote up
/**
 * Generic helper method that takes a string and a mapping function
 * 
 * @param <E>       The desired output type
 * @param parseText The input data to be parsed
 * @param fn        A {@code Function} object to take a string bag and produce an instance of {@code E}
 * @return          An instance of {@code E}
 */
public static <E> E parse(final String parseText, final Function<Map<String, ?>, E> fn) {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new Jdk8Module());
    try {
        return fn.apply(mapper.readValue(parseText, new TypeReference<Map<String, ?>>() {
        }));
    } catch (IOException iox) {
        throw new RuntimeException(iox);
    }
}
 
Example 19
Source File: MappingTest2.java    From jolt with Apache License 2.0 4 votes vote down vote up
@Test
public void testPolymorphicJacksonSerializationAndDeserialization()
{
    ObjectMapper mapper = new ObjectMapper();

    SimpleModule testModule = new SimpleModule("testModule", new Version(1, 0, 0, null, null, null))
            .addDeserializer( QueryFilter.class, new QueryFilterDeserializer() )
            .addSerializer( LogicalFilter2.class, new LogicalFilter2Serializer() );

    mapper.registerModule(testModule);

    // Verifying that we can pass in a custom Mapper and create a new JsonUtil
    JsonUtil jsonUtil = JsonUtils.customJsonUtil( mapper );

    String testFixture = "/jsonUtils/testdomain/two/queryFilter-realAndLogical2.json";

    // TEST JsonUtil and our deserialization logic
    QueryFilter queryFilter = jsonUtil.classpathToType( testFixture, new TypeReference<QueryFilter>() {} );

    // Make sure the hydrated QFilter looks right
    Assert.assertTrue( queryFilter instanceof LogicalFilter2 );
    Assert.assertEquals( QueryParam.AND, queryFilter.getQueryParam() );
    Assert.assertTrue( queryFilter.isLogical() );
    Assert.assertEquals( 3, queryFilter.getFilters().size() );
    Assert.assertNotNull( queryFilter.getFilters().get( QueryParam.OR ) );

    // Make sure one of the top level RealFilters looks right
    QueryFilter productIdFilter = queryFilter.getFilters().get( QueryParam.PRODUCTID );
    Assert.assertTrue( productIdFilter.isReal() );
    Assert.assertEquals( QueryParam.PRODUCTID, productIdFilter.getQueryParam() );
    Assert.assertEquals( "Acme-1234", productIdFilter.getValue() );

    // Make sure the nested OR looks right
    QueryFilter orFilter = queryFilter.getFilters().get( QueryParam.OR );
    Assert.assertTrue( orFilter.isLogical() );
    Assert.assertEquals( QueryParam.OR, orFilter.getQueryParam() );
    Assert.assertEquals( 2, orFilter.getFilters().size() );

    // Make sure nested AND looks right
    QueryFilter nestedAndFilter = orFilter.getFilters().get( QueryParam.AND );
    Assert.assertTrue( nestedAndFilter.isLogical() );
    Assert.assertEquals( QueryParam.AND, nestedAndFilter.getQueryParam() );
    Assert.assertEquals( 2, nestedAndFilter.getFilters().size() );


    // SERIALIZE TO STRING to test serialization logic
    String unitTestString = jsonUtil.toJsonString( queryFilter );

    // LOAD and Diffy the plain vanilla JSON versions of the documents
    Map<String, Object> actual   = JsonUtils.jsonToMap( unitTestString );
    Map<String, Object> expected = JsonUtils.classpathToMap( testFixture );

    // Diffy the vanilla versions
    Diffy.Result result = diffy.diff( expected, actual );
    if (!result.isEmpty()) {
        Assert.fail( "Failed.\nhere is a diff:\nexpected: " + JsonUtils.toJsonString( result.expected ) + "\n  actual: " + JsonUtils.toJsonString( result.actual ) );
    }
}
 
Example 20
Source File: Spotify100Test.java    From heroic with Apache License 2.0 4 votes vote down vote up
private static ObjectMapper expectedObjectMapper() {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new Jdk8Module());
    return mapper;
}