com.fasterxml.jackson.databind.JsonDeserializer Java Examples

The following examples show how to use com.fasterxml.jackson.databind.JsonDeserializer. 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 Project: data-highway   Author: HotelsDotCom   File: SchemaSerializationModuleTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void setupModule() throws JsonMappingException {
  SetupContext context = mock(SetupContext.class);

  underTest.setupModule(context);

  ArgumentCaptor<SimpleSerializers> serializersCaptor = ArgumentCaptor.forClass(SimpleSerializers.class);
  ArgumentCaptor<SimpleDeserializers> deserializersCaptor = ArgumentCaptor.forClass(SimpleDeserializers.class);

  verify(context).addSerializers(serializersCaptor.capture());
  verify(context).addDeserializers(deserializersCaptor.capture());

  JavaType javaType = new ObjectMapper().constructType(Schema.class);

  JsonSerializer<?> serializer = serializersCaptor.getValue().findSerializer(null, javaType, null);
  assertThat(serializer, is(instanceOf(SchemaSerializer.class)));

  JsonDeserializer<?> deserializer = deserializersCaptor.getValue().findBeanDeserializer(javaType, null, null);
  assertThat(deserializer, is(instanceOf(SchemaDeserializer.class)));
}
 
Example #2
Source Project: jackson-modules-java8   Author: FasterXML   File: JSR310StringParsableDeserializer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public JsonDeserializer<?> createContextual(DeserializationContext ctxt,
        BeanProperty property) throws JsonMappingException
{
    JsonFormat.Value format = findFormatOverrides(ctxt, property, handledType());
    JSR310StringParsableDeserializer deser = this;
    if (format != null) {
        if (format.hasLenient()) {
            Boolean leniency = format.getLenient();
            if (leniency != null) {
                deser = this.withLeniency(leniency);
            }
        }
    }
    return deser;
}
 
Example #3
Source Project: dremio-oss   Author: dremio   File: TestMasterDown.java    License: Apache License 2.0 6 votes vote down vote up
private static void initClient() {
  JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
  ObjectMapper objectMapper = JSONUtil.prettyMapper();
  JSONUtil.registerStorageTypes(objectMapper, DremioTest.CLASSPATH_SCAN_RESULT,
      ConnectionReader.of(DremioTest.CLASSPATH_SCAN_RESULT, DremioTest.DEFAULT_SABOT_CONFIG));
  objectMapper.registerModule(
    new SimpleModule()
      .addDeserializer(JobDataFragment.class,
        new JsonDeserializer<JobDataFragment>() {
          @Override
          public JobDataFragment deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
            return jsonParser.readValueAs(DataPOJO.class);
          }
        }
      )
  );
  provider.setMapper(objectMapper);
  client = ClientBuilder.newBuilder().register(provider).register(MultiPartFeature.class).build();
  WebTarget rootTarget = client.target("http://localhost:" + currentDremioDaemon.getWebServer().getPort());
  currentApiV2 = rootTarget.path(API_LOCATION);
}
 
Example #4
Source Project: bootique   Author: bootique   File: JSR310DateTimeDeserializerBase.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public JsonDeserializer<?> createContextual(DeserializationContext ctxt,
                                            BeanProperty property) throws JsonMappingException {
    if (property != null) {
        JsonFormat.Value format = ctxt.getAnnotationIntrospector().findFormat((Annotated) property.getMember());
        if (format != null) {
            if (format.hasPattern()) {
                final String pattern = format.getPattern();
                final Locale locale = format.hasLocale() ? format.getLocale() : ctxt.getLocale();
                DateTimeFormatter df;
                if (locale == null) {
                    df = DateTimeFormatter.ofPattern(pattern);
                } else {
                    df = DateTimeFormatter.ofPattern(pattern, locale);
                }
                return withDateFormat(df);
            }
            // any use for TimeZone?
        }
    }
    return this;
}
 
Example #5
Source Project: jackson-modules-java8   Author: FasterXML   File: DurationDeserializer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public JsonDeserializer<?> createContextual(DeserializationContext ctxt,
                                            BeanProperty property) throws JsonMappingException
{
    JsonFormat.Value format = findFormatOverrides(ctxt, property, handledType());
    DurationDeserializer deser = this;
    if (format != null) {
        if (format.hasLenient()) {
            Boolean leniency = format.getLenient();
            if (leniency != null) {
                deser = deser.withLeniency(leniency);
            }
        }
    }
    return deser;
}
 
Example #6
Source Project: autorest-clientruntime-for-java   Author: Azure   File: AdditionalPropertiesDeserializer.java    License: MIT License 6 votes vote down vote up
/**
 * Gets a module wrapping this serializer as an adapter for the Jackson
 * ObjectMapper.
 *
 * @param mapper the object mapper for default deserializations
 * @return a simple module to be plugged onto Jackson ObjectMapper.
 */
public static SimpleModule getModule(final ObjectMapper mapper) {
    SimpleModule module = new SimpleModule();
    module.setDeserializerModifier(new BeanDeserializerModifier() {
        @Override
        public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
            for (Class<?> c : TypeToken.of(beanDesc.getBeanClass()).getTypes().classes().rawTypes()) {
                Field[] fields = c.getDeclaredFields();
                for (Field field : fields) {
                    if ("additionalProperties".equalsIgnoreCase(field.getName())) {
                        JsonProperty property = field.getAnnotation(JsonProperty.class);
                        if (property != null && property.value().isEmpty()) {
                            return new AdditionalPropertiesDeserializer(beanDesc.getBeanClass(), deserializer, mapper);
                        }
                    }
                }
            }
            return deserializer;
        }
    });
    return module;
}
 
Example #7
Source Project: etherscan-explorer   Author: bing-chou   File: ObjectMapperFactory.java    License: GNU General Public License v3.0 6 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 #8
Source Project: jackson-datatypes-collections   Author: FasterXML   File: GuavaMultisetDeserializer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected T _deserializeContents(JsonParser p, DeserializationContext ctxt) throws IOException,
        JsonProcessingException {
    JsonDeserializer<?> valueDes = _valueDeserializer;
    JsonToken t;
    final TypeDeserializer typeDeser = _valueTypeDeserializer;
    T set = createMultiset();

    while ((t = p.nextToken()) != JsonToken.END_ARRAY) {
        Object value;

        if (t == JsonToken.VALUE_NULL) {
            if (_skipNullValues) {
                continue;
            }
            value = _nullProvider.getNullValue(ctxt);
        } else if (typeDeser == null) {
            value = valueDes.deserialize(p, ctxt);
        } else {
            value = valueDes.deserializeWithType(p, ctxt, typeDeser);
        }
        set.add(value);
    }
    return set;
}
 
Example #9
Source Project: bowman   Author: BlackPepperSoftware   File: RestOperationsFactoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void createInstantiatesObjectMapperWithInlineAssociationDeserializerAwareHandlerInstantiator() {
	ObjectMapper mapper = new ObjectMapper();
	RestTemplate restTemplate = new RestTemplate();
	
	when(mapperFactory.create(any())).thenReturn(mapper);
	when(restTemplateFactory.create(any(), any())).thenReturn(restTemplate);
	
	factory.create();

	ArgumentCaptor<HandlerInstantiator> handlerInstantiator = ArgumentCaptor.forClass(HandlerInstantiator.class);
	verify(mapperFactory).create(handlerInstantiator.capture());
	
	JsonDeserializer<?> result = handlerInstantiator.getValue()
		.deserializerInstance(null, null, InlineAssociationDeserializer.class);
	
	assertThat(result, is(anInlineAssociationDeserializerMatching(
		aRestOperationsMatching(is(restTemplate), is(mapper)), is(proxyFactory))));
}
 
Example #10
Source Project: botbuilder-java   Author: microsoft   File: FlatteningDeserializer.java    License: MIT License 6 votes vote down vote up
/**
 * Gets a module wrapping this serializer as an adapter for the Jackson
 * ObjectMapper.
 *
 * @param mapper the object mapper for default deserializations
 * @return a simple module to be plugged onto Jackson ObjectMapper.
 */
public static SimpleModule getModule(final ObjectMapper mapper) {
    SimpleModule module = new SimpleModule();
    module.setDeserializerModifier(new BeanDeserializerModifier() {
        @Override
        public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
            if (BeanDeserializer.class.isAssignableFrom(deserializer.getClass())) {
                // Apply flattening deserializer on all POJO types.
                return new FlatteningDeserializer(beanDesc.getBeanClass(), deserializer, mapper);
            } else {
                return deserializer;
            }
        }
    });
    return module;
}
 
Example #11
Source Project: nexus-public   Author: sonatype   File: StreamingObjectMapper.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private void readAndWrite(final InputStream input, final OutputStream output) throws IOException {
  try (JsonParser parser = new CurrentPathJsonParser(_jsonFactory.createParser(input))) {

    JsonToken token = _initForReading(parser, valueType);
    DeserializationConfig config = getDeserializationConfig();
    DeserializationContext context = createDeserializationContext(parser, config);

    if (token != VALUE_NULL && token != END_ARRAY && token != END_OBJECT) {

      try (JsonGenerator generator = jsonFactory.createGenerator(output)) {

        generator.writeStartObject();

        beforeDeserialize(generator);

        JsonDeserializer<?> rootDeserializer = _findRootDeserializer(context, valueType);
        deserializeAndSerialize(parser, context, (MapDeserializer) rootDeserializer, generator);

        afterDeserialize(generator);

        context.checkUnresolvedObjectId();
      }
    }

    if (config.isEnabled(FAIL_ON_TRAILING_TOKENS)) {
      _verifyNoTrailingTokens(parser, context, valueType);
    }
  }
}
 
Example #12
Source Project: data-highway   Author: HotelsDotCom   File: RoadModelConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public Module offsetDateTimeModule() {
  return new SimpleModule("OffsetDateTime", unknownVersion(),
      singletonMap(OffsetDateTime.class, new JsonDeserializer<OffsetDateTime>() {
        @Override
        public OffsetDateTime deserialize(JsonParser p, DeserializationContext ctxt)
          throws IOException, JsonProcessingException {
          return OffsetDateTime.parse(p.getValueAsString());
        }
      }));
}
 
Example #13
Source Project: spring4-understanding   Author: langtianya   File: Jackson2ObjectMapperBuilderTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void deserializerByType() throws JsonMappingException {
	JsonDeserializer<Date> deserializer = new DateDeserializers.DateDeserializer();
	ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
			.modules(new ArrayList<>())  // Disable well-known modules detection
			.deserializerByType(Date.class, deserializer).build();
	assertTrue(getDeserializerFactoryConfig(objectMapper).hasDeserializers());
	Deserializers deserializers = getDeserializerFactoryConfig(objectMapper).deserializers().iterator().next();
	assertSame(deserializer, deserializers.findBeanDeserializer(SimpleType.construct(Date.class), null, null));
}
 
Example #14
Source Project: caravan   Author: ctripcorp   File: CustomCollectionDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructor used when creating contextualized instances.
 *
 * @since 2.9
 */
protected CustomCollectionDeserializer(JavaType collectionType,
    JsonDeserializer<Object> valueDeser, TypeDeserializer valueTypeDeser,
    ValueInstantiator valueInstantiator, JsonDeserializer<Object> delegateDeser,
    NullValueProvider nuller, Boolean unwrapSingle) {
  super(collectionType, nuller, unwrapSingle);
  _valueDeserializer = valueDeser;
  _valueTypeDeserializer = valueTypeDeser;
  _valueInstantiator = valueInstantiator;
  _delegateDeserializer = delegateDeser;
}
 
Example #15
Source Project: aws-athena-query-federation   Author: awslabs   File: ObjectMapperFactoryV2.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public JsonDeserializer<Object> createBeanDeserializer(DeserializationContext ctxt, JavaType type, BeanDescription beanDesc)
        throws JsonMappingException
{
    for (Deserializers d  : _factoryConfig.deserializers()) {
        JsonDeserializer<?> deser = d.findBeanDeserializer(type, ctxt.getConfig(), beanDesc);
        if (deser != null) {
            return (JsonDeserializer<Object>) deser;
        }
    }
    throw new IllegalArgumentException("No explicitly configured deserializer for " + type);
}
 
Example #16
Source Project: aws-athena-query-federation   Author: awslabs   File: ObjectMapperFactoryV2.java    License: Apache License 2.0 5 votes vote down vote up
private StrictObjectMapper(BlockAllocator allocator)
{
    super(JSON_FACTORY);
    _serializerFactory = SERIALIZER_FACTORY;

    ImmutableMap<Class<?>, JsonDeserializer<?>> desers = ImmutableMap.of(
            FederationRequest.class, createRequestDeserializer(allocator),
            FederationResponse.class, createResponseDeserializer(allocator),
            LambdaFunctionException.class, new LambdaFunctionExceptionSerDe.Deserializer());
    SimpleDeserializers deserializers = new SimpleDeserializers(desers);
    DeserializerFactoryConfig dConfig = new DeserializerFactoryConfig().withAdditionalDeserializers(deserializers);
    _deserializationContext = new DefaultDeserializationContext.Impl(new StrictDeserializerFactory(dConfig));
    // required by LambdaInvokerFactory
    disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
 
Example #17
Source Project: vividus   Author: vividus-framework   File: WebElementDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property)
{
    JavaType requiredType = property.getType();
    return "Ljava/util/function/Supplier<Ljava/util/Optional<Lorg/openqa/selenium/WebElement;>;>;"
            .equals(requiredType.getGenericSignature()) ? this : null;
}
 
Example #18
Source Project: cyclops   Author: aol   File: LazyEither3Deserializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public LazyEither3<?,?,?> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
  JsonDeserializer ser = ctxt.findRootValueDeserializer(ctxt.getTypeFactory().constructSimpleType(LazyEitherBean.class, new JavaType[0]));
  LazyEitherBean x = (LazyEitherBean)ser.deserialize(p, ctxt);
  if(x.left1!=null){
    return LazyEither3.left1(x.left1);
  }
  if(x.left2!=null){
    return LazyEither3.left2(x.left2);
  }
  return LazyEither3.right(x.right);
}
 
Example #19
Source Project: jackson-datatypes-collections   Author: FasterXML   File: ImmutableSortedBagDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Ref withResolved(
        TypeDeserializer typeDeserializerForValue,
        JsonDeserializer<?> valueDeserializer
) {
    return new ImmutableSortedBagDeserializer.Ref(_elementType, typeDeserializerForValue, valueDeserializer);
}
 
Example #20
Source Project: lams   Author: lamsfoundation   File: UntypedObjectDeserializer.java    License: GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public UntypedObjectDeserializer(UntypedObjectDeserializer base,
        JsonDeserializer<?> mapDeser, JsonDeserializer<?> listDeser,
        JsonDeserializer<?> stringDeser, JsonDeserializer<?> numberDeser)
{
    super(Object.class);
    _mapDeserializer = (JsonDeserializer<Object>) mapDeser;
    _listDeserializer = (JsonDeserializer<Object>) listDeser;
    _stringDeserializer = (JsonDeserializer<Object>) stringDeser;
    _numberDeserializer = (JsonDeserializer<Object>) numberDeser;
    _listType = base._listType;
    _mapType = base._mapType;
    _nonMerging = base._nonMerging;
}
 
Example #21
Source Project: kogito-runtimes   Author: kiegroup   File: KogitoQuarkusObjectMapper.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public JsonDeserializer<?> createContextual( DeserializationContext ctxt, BeanProperty property) throws JsonMappingException {
    CollectionType collectionType = ctxt.getTypeFactory().constructCollectionType(List.class, property.getType().containedType(0));
    DataStreamDeserializer deserializer = new DataStreamDeserializer();
    deserializer.collectionType = collectionType;
    return deserializer;
}
 
Example #22
Source Project: kogito-runtimes   Author: kiegroup   File: KogitoQuarkusObjectMapper.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException {
    CollectionType collectionType = ctxt.getTypeFactory().constructCollectionType(List.class, property.getType().containedType(0));
    DataStoreDeserializer deserializer = new DataStoreDeserializer();
    deserializer.collectionType = collectionType;
    return deserializer;
}
 
Example #23
@Override
protected T _deserializeContents(JsonParser p, DeserializationContext ctxt)
        throws IOException, JsonProcessingException
{
    JsonDeserializer<?> valueDes = _valueDeserializer;
    JsonToken t;
    final TypeDeserializer typeDeser = _valueTypeDeserializer;
    // No way to pass actual type parameter; but does not matter, just
    // compiler-time fluff:
    ImmutableCollection.Builder<Object> builder = createBuilder();

    while ((t = p.nextToken()) != JsonToken.END_ARRAY) {
        Object value;

        if (t == JsonToken.VALUE_NULL) {
            if (_skipNullValues) {
                continue;
            }
            value = _resolveNullToValue(ctxt);
        } else if (typeDeser == null) {
            value = valueDes.deserialize(p, ctxt);
        } else {
            value = valueDes.deserializeWithType(p, ctxt, typeDeser);
        }
        builder.add(value);
    }
    // No class outside of the package will be able to subclass us,
    // and we provide the proper builder for the subclasses we implement.
    @SuppressWarnings("unchecked")
    T collection = (T) builder.build();
    return collection;
}
 
Example #24
Source Project: jackson-datatypes-collections   Author: FasterXML   File: RangeSetDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) {
    final JavaType genericType = ctxt.getContextualType().containedType(0);
    if (genericType == null) return this;
    final RangeSetDeserializer deserializer = new RangeSetDeserializer();
    deserializer.genericRangeListType = ctxt.getTypeFactory().constructCollectionType(List.class,
            ctxt.getTypeFactory().constructParametricType(Range.class, genericType));
    return deserializer;
}
 
Example #25
Source Project: log4j2-elasticsearch   Author: rfoltyns   File: JacksonHandlerInstantiatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void deserializerInstanceReturnsNull() {

    // given
    VirtualProperty[] customProperties = new VirtualProperty[0];
    Log4j2Lookup valueResolver = new Log4j2Lookup(null);
    JacksonHandlerInstantiator handlerInstantiator = createTestHandlerInstantiator(customProperties, valueResolver);

    // when
    JsonDeserializer<?> result = handlerInstantiator.deserializerInstance(null, null, null);

    // then
    Assert.assertNull(result);

}
 
Example #26
Source Project: batfish   Author: batfish   File: RangeSetDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected @Nonnull StdDelegatingDeserializer<RangeSet<?>> withDelegate(
    Converter<Object, RangeSet<?>> converter,
    JavaType delegateType,
    JsonDeserializer<?> delegateDeserializer) {
  return new StdDelegatingDeserializer<>(converter, delegateType, delegateDeserializer);
}
 
Example #27
Source Project: jackson-datatypes-collections   Author: FasterXML   File: ImmutableSortedMapDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public GuavaMapDeserializer<ImmutableSortedMap<Object, Object>> withResolved(KeyDeserializer keyDeser,
        JsonDeserializer<?> valueDeser, TypeDeserializer typeDeser,
        NullValueProvider nuller)
{
    return new ImmutableSortedMapDeserializer(_containerType, keyDeser, valueDeser, typeDeser, nuller);
}
 
Example #28
Source Project: bowman   Author: BlackPepperSoftware   File: RestOperationsFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void createInstantiatesObjectMapperWithResourceDeserializerAwareHandlerInstantiator() {
	factory.create();
	
	ArgumentCaptor<HandlerInstantiator> handlerInstantiator = ArgumentCaptor.forClass(HandlerInstantiator.class);
	verify(mapperFactory).create(handlerInstantiator.capture());
	
	JsonDeserializer<?> result = handlerInstantiator.getValue()
		.deserializerInstance(null, null, ResourceDeserializer.class);
	
	assertThat(result, is(aResourceDeserializerMatching(instanceOf(DefaultTypeResolver.class),
		is(configuration))));
}
 
Example #29
Source Project: cyclops   Author: aol   File: IorDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Ior<?,?> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
  JsonDeserializer ser = ctxt.findRootValueDeserializer(ctxt.getTypeFactory().constructSimpleType(IorBean.class, new JavaType[0]));
  IorBean x = (IorBean)ser.deserialize(p, ctxt);
  if(x.left!=null && x.right==null){
    return Ior.left(x.left);
  }
  if(x.left==null && x.right!=null){
    return Ior.right(x.right);
  }
  return Ior.both(x.left,x.right);
}
 
Example #30
Source Project: openapi-generator   Author: OpenAPITools   File: CustomInstantDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected JsonDeserializer<T> withDateFormat(DateTimeFormatter dtf) {
  if (dtf == _formatter) {
    return this;
  }
  return new CustomInstantDeserializer<T>(this, dtf);
}