Java Code Examples for com.fasterxml.jackson.databind.JsonDeserializer

The following examples show how to use com.fasterxml.jackson.databind.JsonDeserializer. These examples are extracted from open source projects. 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
@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
@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   Source 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   Source 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
@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
/**
 * 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
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
@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   Source 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   Source 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
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   Source 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
@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   Source 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
@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
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   Source 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   Source 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
@Override
protected Ref withResolved(
        TypeDeserializer typeDeserializerForValue,
        JsonDeserializer<?> valueDeserializer
) {
    return new ImmutableSortedBagDeserializer.Ref(_elementType, typeDeserializerForValue, valueDeserializer);
}
 
Example 20
@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   Source 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   Source 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
@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
@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   Source 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
@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   Source 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   Source 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
@Override
protected JsonDeserializer<T> withDateFormat(DateTimeFormatter dtf) {
  if (dtf == _formatter) {
    return this;
  }
  return new CustomInstantDeserializer<T>(this, dtf);
}