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 File: RestOperationsFactoryTest.java    From bowman with 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 #2
Source File: SchemaSerializationModuleTest.java    From data-highway with 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 #3
Source File: AdditionalPropertiesDeserializer.java    From autorest-clientruntime-for-java with 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 #4
Source File: GuavaMultisetDeserializer.java    From jackson-datatypes-collections with 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 #5
Source File: JSR310StringParsableDeserializer.java    From jackson-modules-java8 with 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 #6
Source File: FlatteningDeserializer.java    From botbuilder-java with 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 #7
Source File: DurationDeserializer.java    From jackson-modules-java8 with 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 #8
Source File: JSR310DateTimeDeserializerBase.java    From bootique with 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 #9
Source File: ObjectMapperFactory.java    From etherscan-explorer with 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 #10
Source File: TestMasterDown.java    From dremio-oss with 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 #11
Source File: ConvertingDeserializer.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Override
public JsonDeserializer<?> createContextual(DeserializationContext deserializationContext, BeanProperty beanProperty) {
    JavaType javaType = deserializationContext.getContextualType() != null ? deserializationContext.getContextualType() : extractType(beanProperty.getMember());
    Annotation[] annotations = annotations(beanProperty);
    AnnotatedType detectedType = environment.typeTransformer.transform(ClassUtils.addAnnotations(TypeUtils.toJavaType(javaType), annotations));
    JavaType substituteType = deserializationContext.getTypeFactory().constructType(environment.getMappableInputType(detectedType).getType());
    if (inputConverter.supports(detectedType)) {
        return new ConvertingDeserializer(detectedType, substituteType, inputConverter, environment, objectMapper);
    } else {
        return new DefaultDeserializer(javaType);
    }
}
 
Example #12
Source File: JsonUtility.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
/**
 * 注册指定类型的序列化器与反序列化器
 * 
 * @param clazz
 * @param deserializer
 * @param serializer
 */
public static <T> void registerModule(Class<T> clazz, JsonDeserializer<T> deserializer, JsonSerializer<T> serializer) {
    if (deserializer != null) {
        TYPE_MODULE.addDeserializer(clazz, deserializer);
    }
    if (serializer != null) {
        TYPE_MODULE.addSerializer(clazz, serializer);
    }
}
 
Example #13
Source File: JacksonHandlerInstantiatorTest.java    From log4j2-elasticsearch with 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 #14
Source File: RangeSetDeserializer.java    From jackson-datatypes-collections with 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 #15
Source File: TypeDeserializerBase.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @since 2.8
 */
protected TypeDeserializerBase(JavaType baseType, TypeIdResolver idRes,
        String typePropertyName, boolean typeIdVisible, JavaType defaultImpl)
{
    _baseType = baseType;
    _idResolver = idRes;
    _typePropertyName = ClassUtil.nonNullString(typePropertyName);
    _typeIdVisible = typeIdVisible;
    // defaults are fine, although shouldn't need much concurrency
    _deserializers = new ConcurrentHashMap<String, JsonDeserializer<Object>>(16, 0.75f, 2);
    _defaultImpl = defaultImpl;
    _property = null;
}
 
Example #16
Source File: GuavaImmutableCollectionDeserializer.java    From jackson-datatypes-collections with Apache License 2.0 5 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;
    // 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 #17
Source File: LazyEither3Deserializer.java    From cyclops with 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 #18
Source File: RangeSetDeserializer.java    From batfish with 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 #19
Source File: KogitoQuarkusObjectMapper.java    From kogito-runtimes with 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 #20
Source File: AWSServiceSerdeModule.java    From cloudformation-cli-java-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public JsonDeserializer<?> findBeanDeserializer(JavaType type, DeserializationConfig config, BeanDescription beanDesc)
    throws JsonMappingException {
    if (SdkPojo.class.isAssignableFrom(type.getRawClass()) && !SdkBuilder.class.isAssignableFrom(type.getRawClass())) {
        return new SdkPojoDeserializer(type);
    }
    return null;
}
 
Example #21
Source File: ImmutableSortedMapDeserializer.java    From jackson-datatypes-collections with 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 #22
Source File: CustomInstantDeserializer.java    From openapi-generator with 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);
}
 
Example #23
Source File: RosettaAnnotationIntrospector.java    From Rosetta with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public JsonDeserializer<?> findDeserializer(Annotated a) {
  StoredAsJson storedAsJson = a.getAnnotation(StoredAsJson.class);
  RosettaDeserialize rosettaDeserialize = a.getAnnotation(RosettaDeserialize.class);
  if (storedAsJson != null && rosettaDeserialize != null) {
    throw new IllegalArgumentException("Cannot have @StoredAsJson as well as @RosettaDeserialize annotations on the same entry");
  }
  if (storedAsJson != null) {
    if (a instanceof AnnotatedMethod) {
      a = getAnnotatedTypeFromAnnotatedMethod((AnnotatedMethod) a);
    }

    String empty = StoredAsJson.NULL.equals(storedAsJson.empty()) ? "null" : storedAsJson.empty();
    return new StoredAsJsonDeserializer(a.getRawType(), getType(a), empty, objectMapper);
  }

  if (rosettaDeserialize != null) {
    Class<? extends JsonDeserializer> klass = rosettaDeserialize.using();
    if (klass != JsonDeserializer.None.class) {
      return ClassUtil.createInstance(
          klass,
          objectMapper.getDeserializationConfig().canOverrideAccessModifiers());
    }
  }

  return null;
}
 
Example #24
Source File: CustomInstantDeserializer.java    From openapi-generator with 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);
}
 
Example #25
Source File: RestOperationsFactoryTest.java    From bowman with 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 #26
Source File: IorDeserializer.java    From cyclops with 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 #27
Source File: CustomInstantDeserializer.java    From openapi-generator with 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);
}
 
Example #28
Source File: DeserializerModifier.java    From Sparkplug with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
    if (Metric.class.equals(beanDesc.getBeanClass())) {
        return new MetricDeserializer(deserializer);
    }

    return super.modifyDeserializer(config, beanDesc, deserializer);
}
 
Example #29
Source File: CustomInstantDeserializer.java    From openapi-generator with 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);
}
 
Example #30
Source File: CompositeDeserializers.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Override
public JsonDeserializer<?> findReferenceDeserializer(ReferenceType refType, DeserializationConfig config,
                                                     BeanDescription beanDesc, TypeDeserializer contentTypeDeserializer,
                                                     JsonDeserializer<?> contentDeserializer) throws JsonMappingException {
    for (Deserializers deserializers : deserializersList) {
        JsonDeserializer<?> deserializer = deserializers.findReferenceDeserializer(refType, config, beanDesc, contentTypeDeserializer, contentDeserializer);
        if (deserializer != null) {
            return deserializer;
        }
    }
    return null;
}