下面列出了怎么用com.fasterxml.jackson.databind.BeanProperty的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
// 为空直接跳过
if (property == null) {
return prov.findNullValueSerializer(property);
}
// 非 Double 类直接跳过
if (Objects.equals(property.getType().getRawClass(), Double.class)) {
DoubleSpecify doubleSpecify = property.getAnnotation(DoubleSpecify.class);
if (doubleSpecify == null) {
doubleSpecify = property.getContextAnnotation(DoubleSpecify.class);
}
// 如果能得到注解,就将注解的 value 传入 DoubleSpecifySerialize
if (doubleSpecify != null) {
return new DoubleSpecifySerialize(doubleSpecify.value());
}
}
return prov.findValueSerializer(property.getType(), property);
}
@Override
public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
// 为空直接跳过
if (property == null) {
return prov.findNullValueSerializer(property);
}
// 非 BigDecimal 类直接跳过
if (Objects.equals(property.getType().getRawClass(), BigDecimal.class)) {
BigDecimalSpecify doubleSpecify = property.getAnnotation(BigDecimalSpecify.class);
if (doubleSpecify == null) {
doubleSpecify = property.getContextAnnotation(BigDecimalSpecify.class);
}
// 如果能得到注解,就将注解的 value 传入 BigDecimalSpecifySerialize
if (doubleSpecify != null) {
return new BigDecimalSpecifySerialize(doubleSpecify.value());
}
}
return prov.findValueSerializer(property.getType(), property);
}
@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;
}
/**
* We only use contextualization for optimizing the case where no customization
* occurred; if so, can slip in a more streamlined version.
*/
@Override
public JsonDeserializer<?> createContextual(DeserializationContext ctxt,
BeanProperty property) throws JsonMappingException
{
// 14-Jun-2017, tatu: [databind#1625]: may want to block merging, for root value
boolean preventMerge = (property == null)
&& Boolean.FALSE.equals(ctxt.getConfig().getDefaultMergeable(Object.class));
// 20-Apr-2014, tatu: If nothing custom, let's use "vanilla" instance,
// simpler and can avoid some of delegation
if ((_stringDeserializer == null) && (_numberDeserializer == null)
&& (_mapDeserializer == null) && (_listDeserializer == null)
&& getClass() == UntypedObjectDeserializer.class) {
return Vanilla.instance(preventMerge);
}
if (preventMerge != _nonMerging) {
return new UntypedObjectDeserializer(this, preventMerge);
}
return this;
}
@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;
}
@Override
public void customizeSchema(BeanProperty property, JsonSchema jsonschema) {
Optional.ofNullable(property.getAnnotation(Password.class)).ifPresent(annotation -> {
if (annotation.title() != null) {
((StringSchema) jsonschema).setTitle(annotation.title());
}
if (annotation.pattern() != null) {
((StringSchema) jsonschema).setPattern(annotation.pattern());
}
if (annotation.minLenght() != 0) {
((StringSchema) jsonschema).setMinLength(annotation.minLenght());
}
if (annotation.maxLenght() != Integer.MAX_VALUE) {
((StringSchema) jsonschema).setMaxLength(annotation.maxLenght());
}
});
}
@Override
public void customizeSchema(BeanProperty property, JsonSchema jsonschema) {
TextField annotation = property.getAnnotation(TextField.class);
if (annotation != null) {
if (annotation.title() != null) {
((StringSchema) jsonschema).setTitle(annotation.title());
}
if (annotation.pattern() != null) {
((StringSchema) jsonschema).setPattern(annotation.pattern());
}
if (annotation.minLenght() != 0) {
((StringSchema) jsonschema).setMinLength(annotation.minLenght());
}
if (annotation.maxLenght() != Integer.MAX_VALUE) {
((StringSchema) jsonschema).setMaxLength(annotation.maxLenght());
}
}
}
@SuppressWarnings("unchecked")
@Override
public JsonDeserializer<T> createContextual(DeserializationContext ctxt,
BeanProperty property) throws JsonMappingException
{
InstantDeserializer<T> deserializer =
(InstantDeserializer<T>)super.createContextual(ctxt, property);
if (deserializer != this) {
JsonFormat.Value val = findFormatOverrides(ctxt, property, handledType());
if (val != null) {
deserializer = new InstantDeserializer<>(deserializer, val.getFeature(JsonFormat.Feature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE));
if (val.hasLenient()) {
Boolean leniency = val.getLenient();
if (leniency != null) {
deserializer = deserializer.withLeniency(leniency);
}
}
}
}
return deserializer;
}
@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;
}
void shouldReturnTypeBasedDeserializer(String type, JsonDeserializer<?> expected)
{
BeanProperty property = mock(BeanProperty.class);
JavaType javaType = mock(JavaType.class);
when(property.getType()).thenReturn(javaType);
when(javaType.getGenericSignature()).thenReturn(type);
assertEquals(expected, deserializer.createContextual(null, property));
}
@Override
protected ReferenceTypeSerializer<Eval<?>> withResolved(BeanProperty prop,
TypeSerializer vts, JsonSerializer<?> valueSer,
NameTransformer unwrapper)
{
return new EvalSerializer(this, prop, vts, valueSer, unwrapper,
_suppressableValue, _suppressNulls);
}
@Override
public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException {
JavaType javaType = property.getType().containedType(0);
SingletonStoreDeserializer deserializer = new SingletonStoreDeserializer();
deserializer.javaType = javaType;
return deserializer;
}
protected TrampolineSerializer(TrampolineSerializer base, BeanProperty property,
TypeSerializer vts, JsonSerializer<?> valueSer, NameTransformer unwrapper,
Object suppressablTrampolineue, boolean suppressNulls)
{
super(base, property, vts, valueSer, unwrapper,
suppressablTrampolineue, suppressNulls);
}
@Override
public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException {
JavaType javaType = property.getType().containedType(0);
SingletonStoreDeserializer deserializer = new KogitoModule.SingletonStoreDeserializer();
deserializer.javaType = javaType;
return deserializer;
}
@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);
}
}
@Override
protected ReferenceTypeSerializer<Option<?>> withResolved(BeanProperty prop,
TypeSerializer vts, JsonSerializer<?> valueSer,
NameTransformer unwrapper)
{
return new OptionSerializer(this, prop, vts, valueSer, unwrapper,
_suppressableValue, _suppressNulls);
}
protected RefRefMapIterableSerializer(
RefRefMapIterableSerializer src, BeanProperty property,
JsonSerializer<?> keySerializer, TypeSerializer vts, JsonSerializer<?> valueSerializer,
Set<String> ignoredEntries
) {
super(src, property, keySerializer, vts, valueSerializer, ignoredEntries);
}
@Override
public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException {
if (property != null) {
IgnoreXSS annotation = property.getAnnotation(IgnoreXSS.class);
if (annotation != null) {
return StringDeserializer.instance;
}
}
return this;
}
@Override
public JsonDeserializer<?> createContextual(DeserializationContext ctxt,
BeanProperty property) {
JavaType contextualType = ctxt.getContextualType();
checkArgument(contextualType.isEnumType());
return createFromType(contextualType);
}
@Override
public JsonDeserializer<?> createContextual(DeserializationContext ctxt,
BeanProperty property) {
JavaType contextualType = ctxt.getContextualType();
checkArgument(contextualType.isEnumType());
return createFromType(contextualType);
}
@Override
public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property)
throws JsonMappingException {
checkNotNull(ctxt, "Null DeserializationContext.");
JavaType type = checkNotNull(ctxt.getContextualType(), "Invalid type: %s", getClass());
JavaType[] params = type.findTypeParameters(ValueProvider.class);
if (params.length != 1) {
throw new RuntimeException("Unable to derive type for ValueProvider: " + type.toString());
}
JavaType param = params[0];
return new Deserializer(param);
}
@Test
public void testCreation() throws IOException {
String desc = "{\n" +
" \"type\": \"default\",\n" +
" \"indexTypeMap\":{\"routingkey1\":\"index1:type1\", \"routingkey2\":\"index2:type2\"},\n" +
" \"idFields\":{\"routingkey\": [\"f1\", \"f2\", \"ts_minute\"]},\n" +
" \"timestamp\": {\"field\":\"ts\"},\n" +
" \"indexSuffixFormatter\":{\"type\": \"date\", \"properties\":{\"dateFormat\":\"YYYYMMdd\"}}\n" +
"}";
jsonMapper.setInjectableValues(new InjectableValues() {
@Override
public Object findInjectableValue(
Object valueId,
DeserializationContext ctxt,
BeanProperty forProperty,
Object beanInstance
) {
if (valueId.equals(ObjectMapper.class.getCanonicalName())) {
return jsonMapper;
} else {
return null;
}
}
});
DateTime dt = new DateTime("2014-10-12T12:12:12.000Z");
Map<String, Object> msg = new ImmutableMap.Builder<String, Object>()
.put("f1", "v1")
.put("f2", "v2")
.put("f3", "v3")
.put("ts", dt.getMillis())
.build();
IndexInfoBuilder builder = jsonMapper.readValue(desc, new TypeReference<IndexInfoBuilder>(){});
IndexInfo info = builder.create(new Message("routingkey", jsonMapper.writeValueAsBytes(msg)));
assertEquals(info.getId(), ("v1v2" + dt.getMillis() / 60000));
}
protected TypeDeserializerBase(TypeDeserializerBase src, BeanProperty property)
{
_baseType = src._baseType;
_idResolver = src._idResolver;
_typePropertyName = src._typePropertyName;
_typeIdVisible = src._typeIdVisible;
_deserializers = src._deserializers;
_defaultImpl = src._defaultImpl;
_defaultImplDeserializer = src._defaultImplDeserializer;
_property = property;
}
@Override
public TypeDeserializer forProperty(BeanProperty prop) {
if (prop == _property) { // usually if it's null
return this;
}
return new AsExternalTypeDeserializer(this, prop);
}
@Override
public JsonDeserializer<?> createContextual( DeserializationContext ctxt, BeanProperty property ) throws JsonMappingException {
if ( ctxt.getContextualType() == null || ctxt.getContextualType().containedType( 0 ) == null ) {
throw JsonMappingException.from( ctxt, "Cannot deserialize Ref<T>. Cannot find the Generic Type T." );
}
return new RefStdDeserializer( ctxt.getContextualType().containedType( 0 ) );
}
@Override
public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) {
if (property == null) return this;
final RangeSetSerializer serializer = new RangeSetSerializer();
serializer.genericRangeListType = prov.getTypeFactory()
.constructCollectionType(List.class,
prov.getTypeFactory().constructParametricType(
Range.class, property.getType().containedType(0)));
return serializer;
}
/**
* @deprecated since 2.6
*/
@Deprecated // since 2.6
public CollectionSerializer(JavaType elemType, boolean staticTyping, TypeSerializer vts,
BeanProperty property, JsonSerializer<Object> valueSerializer) {
// note: assumption is 'property' is always passed as null
this(elemType, staticTyping, vts, valueSerializer);
}
@Override
protected ReferenceTypeSerializer<Trampoline<?>> withResolved(BeanProperty prop,
TypeSerializer vts, JsonSerializer<?> valueSer,
NameTransformer unwrapper)
{
return new TrampolineSerializer(this, prop, vts, valueSer, unwrapper,
_suppressableValue, _suppressNulls);
}
@Override
public JsonSerializer<?> createContextual(SerializerProvider provider, BeanProperty property)
throws JsonMappingException {
if (delegate instanceof ContextualSerializer) {
return new DeepEmptyCheckingSerializer<>(
((ContextualSerializer) delegate).createContextual(provider, property));
}
return this;
}
private boolean shouldSkip(BeanProperty prop) {
Class<?> rawClass = prop.getType().getContentType() != null
? prop.getType().getContentType().getRawClass()
: prop.getType().getRawClass();
return SKIPPED_FIELDS.contains(prop.getName())
|| SKIPPED_CLASSES.contains(rawClass.getCanonicalName());
}