下面列出了com.fasterxml.jackson.annotation.JsonFormat#Value ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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;
}
@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;
}
/**
* To support some level of per-property configuration, we will need
* to make things contextual. We are limited to "textual vs index"
* choice here, however.
*/
@Override
public JsonSerializer<?> createContextual(SerializerProvider serializers,
BeanProperty property) throws JsonMappingException
{
JsonFormat.Value format = findFormatOverrides(serializers,
property, handledType());
if (format != null) {
Class<?> type = handledType();
Boolean serializeAsIndex = _isShapeWrittenUsingIndex(type,
format, false, _serializeAsIndex);
if (serializeAsIndex != _serializeAsIndex) {
return new EnumSerializer(_values, serializeAsIndex);
}
}
return this;
}
@Override
public JsonSerializer<?> createContextual(SerializerProvider serializers,
BeanProperty property) throws JsonMappingException
{
Boolean unwrapSingle = null;
// First: if we have a property, may have property-annotation overrides
if (property != null) {
JsonFormat.Value format = findFormatOverrides(serializers, property, handledType());
if (format != null) {
unwrapSingle = format.getFeature(JsonFormat.Feature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED);
if (unwrapSingle != _unwrapSingle) {
return _withResolved(property, unwrapSingle);
}
}
}
return this;
}
@Override
@Deprecated
public final JsonFormat.Value findFormatOverrides(AnnotationIntrospector intr) {
JsonFormat.Value f = null;
if (intr != null) {
AnnotatedMember member = getMember();
if (member != null) {
f = intr.findFormat(member);
}
}
if (f == null) {
f = EMPTY_FORMAT;
}
return f;
}
private static TypeProcessor createSpecificTypeProcessor() {
return new TypeProcessor.Chain(
new ExcludingTypeProcessor(Arrays.asList(JsonNode.class.getName())),
new TypeProcessor() {
@Override
public TypeProcessor.Result processType(Type javaType, TypeProcessor.Context context) {
if (context.getTypeContext() instanceof Jackson2TypeContext) {
final Jackson2TypeContext jackson2TypeContext = (Jackson2TypeContext) context.getTypeContext();
if (!jackson2TypeContext.disableObjectIdentityFeature) {
final Type resultType = jackson2TypeContext.parser.processIdentity(javaType, jackson2TypeContext.beanPropertyWriter);
if (resultType != null) {
return context.withTypeContext(null).processType(resultType);
}
}
// Map.Entry
final Class<?> rawClass = Utils.getRawClassOrNull(javaType);
if (rawClass != null && Map.Entry.class.isAssignableFrom(rawClass)) {
final ObjectMapper objectMapper = jackson2TypeContext.parser.objectMapper;
final SerializationConfig serializationConfig = objectMapper.getSerializationConfig();
final BeanDescription beanDescription = serializationConfig
.introspect(TypeFactory.defaultInstance().constructType(rawClass));
final JsonFormat.Value formatOverride = serializationConfig.getDefaultPropertyFormat(Map.Entry.class);
final JsonFormat.Value formatFromAnnotation = beanDescription.findExpectedFormat(null);
final JsonFormat.Value format = JsonFormat.Value.merge(formatFromAnnotation, formatOverride);
if (format.getShape() != JsonFormat.Shape.OBJECT) {
final Type mapType = Utils.replaceRawClassInType(javaType, Map.class);
return context.processType(mapType);
}
}
}
return null;
}
}
);
}
@Override
public JsonFormat.Value findFormat(Annotated ann) {
JsonFormat.Value v1 = _primary.findFormat(ann);
JsonFormat.Value v2 = _secondary.findFormat(ann);
if (v2 == null) { // shouldn't occur but just in case
return v1;
}
return v2.withOverrides(v1);
}
@Override
public JsonSerializer<?> createContextual(SerializerProvider serializers,
BeanProperty property) throws JsonMappingException
{
JsonFormat.Value format = findFormatOverrides(serializers,
property, Boolean.class);
if (format != null) {
JsonFormat.Shape shape = format.getShape();
if (shape.isNumeric()) {
return new AsNumber(_forPrimitive);
}
}
return this;
}
/**
* Factory method used by {@link com.fasterxml.jackson.databind.ser.BasicSerializerFactory}
* for constructing serializer instance of Enum types.
*
* @since 2.1
*/
@SuppressWarnings("unchecked")
public static EnumSerializer construct(Class<?> enumClass, SerializationConfig config,
BeanDescription beanDesc, JsonFormat.Value format)
{
/* 08-Apr-2015, tatu: As per [databind#749], we cannot statically determine
* between name() and toString(), need to construct `EnumValues` with names,
* handle toString() case dynamically (for example)
*/
EnumValues v = EnumValues.constructFromName(config, (Class<Enum<?>>) enumClass);
Boolean serializeAsIndex = _isShapeWrittenUsingIndex(enumClass, format, true, null);
return new EnumSerializer(v, serializeAsIndex);
}
@Override
public JsonSerializer<?> createContextual(SerializerProvider prov,
BeanProperty property) throws JsonMappingException
{
JsonFormat.Value format = findFormatOverrides(prov, property, handledType());
if (format != null) {
switch (format.getShape()) {
case STRING:
return ToStringSerializer.instance;
default:
}
}
return this;
}
@Override
public JsonSerializer<?> findReferenceSerializer(SerializationConfig config,
ReferenceType refType, BeanDescription beanDesc, JsonFormat.Value formatOverrides,
TypeSerializer contentTypeSerializer, JsonSerializer<Object> contentValueSerializer)
{
final Class<?> raw = refType.getRawClass();
if (Optional.class.isAssignableFrom(raw)) {
boolean staticTyping = (contentTypeSerializer == null)
&& config.isEnabled(MapperFeature.USE_STATIC_TYPING);
return new GuavaOptionalSerializer(refType, staticTyping,
contentTypeSerializer, contentValueSerializer);
}
return null;
}
@SuppressWarnings("unchecked")
@Override
public JsonSerializer<?> createContextual(SerializerProvider serializers,
BeanProperty property)
throws JsonMappingException
{
JsonSerializer<?> ser = null;
Boolean unwrapSingle = null;
if (property != null) {
final AnnotationIntrospector intr = serializers.getAnnotationIntrospector();
AnnotatedMember m = property.getMember();
if (m != null) {
Object serDef = intr.findContentSerializer(m);
if (serDef != null) {
ser = serializers.serializerInstance(m, serDef);
}
}
}
JsonFormat.Value format = findFormatOverrides(serializers, property, handledType());
if (format != null) {
unwrapSingle = format.getFeature(JsonFormat.Feature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED);
}
// [databind#124]: May have a content converter
ser = findContextualConvertingSerializer(serializers, property, ser);
if (ser == null) {
ser = serializers.findValueSerializer(String.class, property);
}
// Optimization: default serializer just writes String, so we can avoid a call:
if (isDefaultSerializer(ser)) {
if (unwrapSingle == _unwrapSingle) {
return this;
}
return _withResolved(property, unwrapSingle);
}
// otherwise...
// note: will never have TypeSerializer, because Strings are "natural" type
return new CollectionSerializer(serializers.constructType(String.class),
true, /*TypeSerializer*/ null, (JsonSerializer<Object>) ser);
}
/**
* Helper method that handles configuration details when constructing serializers for
* {@link java.util.List} types that support efficient by-index access
*
* @since 2.1
*/
protected JsonSerializer<?> buildCollectionSerializer(SerializerProvider prov,
CollectionType type, BeanDescription beanDesc, boolean staticTyping,
TypeSerializer elementTypeSerializer, JsonSerializer<Object> elementValueSerializer)
throws JsonMappingException
{
SerializationConfig config = prov.getConfig();
JsonSerializer<?> ser = null;
// Order of lookups:
// 1. Custom serializers
// 2. Annotations (@JsonValue, @JsonDeserialize)
// 3. Defaults
for (Serializers serializers : customSerializers()) { // (1) Custom
ser = serializers.findCollectionSerializer(config,
type, beanDesc, elementTypeSerializer, elementValueSerializer);
if (ser != null) {
break;
}
}
if (ser == null) {
ser = findSerializerByAnnotations(prov, type, beanDesc); // (2) Annotations
if (ser == null) {
// We may also want to use serialize Collections "as beans", if (and only if)
// this is specified with `@JsonFormat(shape=Object)`
JsonFormat.Value format = beanDesc.findExpectedFormat(null);
if ((format != null) && format.getShape() == JsonFormat.Shape.OBJECT) {
return null;
}
Class<?> raw = type.getRawClass();
if (EnumSet.class.isAssignableFrom(raw)) {
// this may or may not be available (Class doesn't; type of field/method does)
JavaType enumType = type.getContentType();
// and even if nominally there is something, only use if it really is enum
if (!enumType.isEnumType()) {
enumType = null;
}
ser = buildEnumSetSerializer(enumType);
} else {
Class<?> elementRaw = type.getContentType().getRawClass();
if (isIndexedList(raw)) {
if (elementRaw == String.class) {
// [JACKSON-829] Must NOT use if we have custom serializer
if (ClassUtil.isJacksonStdImpl(elementValueSerializer)) {
ser = IndexedStringListSerializer.instance;
}
} else {
ser = buildIndexedListSerializer(type.getContentType(), staticTyping,
elementTypeSerializer, elementValueSerializer);
}
} else if (elementRaw == String.class) {
// [JACKSON-829] Must NOT use if we have custom serializer
if (ClassUtil.isJacksonStdImpl(elementValueSerializer)) {
ser = StringCollectionSerializer.instance;
}
}
if (ser == null) {
ser = buildCollectionSerializer(type.getContentType(), staticTyping,
elementTypeSerializer, elementValueSerializer);
}
}
}
}
// [databind#120]: Allow post-processing
if (_factoryConfig.hasSerializerModifiers()) {
for (BeanSerializerModifier mod : _factoryConfig.serializerModifiers()) {
ser = mod.modifyCollectionSerializer(config, type, beanDesc, ser);
}
}
return ser;
}
/**
* Method for checking if we can determine serializer to use based on set of
* known primary types, checking for set of known base types (exact matches
* having been compared against with <code>findSerializerByLookup</code>).
* This does not include "secondary" interfaces, but
* mostly concrete or abstract base classes.
*/
protected final JsonSerializer<?> findSerializerByPrimaryType(SerializerProvider prov,
JavaType type, BeanDescription beanDesc,
boolean staticTyping)
throws JsonMappingException
{
Class<?> raw = type.getRawClass();
// Then check for optional/external serializers
JsonSerializer<?> ser = findOptionalStdSerializer(prov, type, beanDesc, staticTyping);
if (ser != null) {
return ser;
}
if (Calendar.class.isAssignableFrom(raw)) {
return CalendarSerializer.instance;
}
if (java.util.Date.class.isAssignableFrom(raw)) {
return DateSerializer.instance;
}
if (Map.Entry.class.isAssignableFrom(raw)) {
// 18-Oct-2015, tatu: With 2.7, need to dig type info:
JavaType mapEntryType = type.findSuperType(Map.Entry.class);
// 28-Apr-2015, tatu: TypeFactory does it all for us already so
JavaType kt = mapEntryType.containedTypeOrUnknown(0);
JavaType vt = mapEntryType.containedTypeOrUnknown(1);
return buildMapEntrySerializer(prov, type, beanDesc, staticTyping, kt, vt);
}
if (ByteBuffer.class.isAssignableFrom(raw)) {
return new ByteBufferSerializer();
}
if (InetAddress.class.isAssignableFrom(raw)) {
return new InetAddressSerializer();
}
if (InetSocketAddress.class.isAssignableFrom(raw)) {
return new InetSocketAddressSerializer();
}
if (TimeZone.class.isAssignableFrom(raw)) {
return new TimeZoneSerializer();
}
if (java.nio.charset.Charset.class.isAssignableFrom(raw)) {
return ToStringSerializer.instance;
}
if (Number.class.isAssignableFrom(raw)) {
// 21-May-2014, tatu: Couple of alternatives actually
JsonFormat.Value format = beanDesc.findExpectedFormat(null);
if (format != null) {
switch (format.getShape()) {
case STRING:
return ToStringSerializer.instance;
case OBJECT: // need to bail out to let it be serialized as POJO
case ARRAY: // or, I guess ARRAY; otherwise no point in speculating
return null;
default:
}
}
return NumberSerializer.instance;
}
if (Enum.class.isAssignableFrom(raw)) {
return buildEnumSerializer(prov.getConfig(), type, beanDesc);
}
return null;
}
@Override
public JsonSerializer<?> createContextual(SerializerProvider serializers,
BeanProperty property)
throws JsonMappingException
{
TypeSerializer vts = _valueTypeSerializer;
if (vts != null) {
vts = vts.forProperty(property);
}
JsonSerializer<?> ser = null;
Boolean unwrapSingle = null;
// First: if we have a property, may have property-annotation overrides
if (property != null) {
AnnotatedMember m = property.getMember();
final AnnotationIntrospector intr = serializers.getAnnotationIntrospector();
if (m != null) {
Object serDef = intr.findContentSerializer(m);
if (serDef != null) {
ser = serializers.serializerInstance(m, serDef);
}
}
}
JsonFormat.Value format = findFormatOverrides(serializers, property, handledType());
if (format != null) {
unwrapSingle = format.getFeature(JsonFormat.Feature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED);
}
if (ser == null) {
ser = _elementSerializer;
}
// [databind#124]: May have a content converter
ser = findContextualConvertingSerializer(serializers, property, ser);
if (ser == null) {
// 30-Sep-2012, tatu: One more thing -- if explicit content type is annotated,
// we can consider it a static case as well.
if (_elementType != null) {
if (_staticTyping && !_elementType.isJavaLangObject()) {
ser = serializers.findValueSerializer(_elementType, property);
}
}
}
return withResolved(property, vts, ser, unwrapSingle);
}
/**
* Helper method that handles configuration details when constructing serializers for
* {@link java.util.Map} types.
*/
protected JsonSerializer<?> buildMapSerializer(SerializerProvider prov,
MapType type, BeanDescription beanDesc,
boolean staticTyping, JsonSerializer<Object> keySerializer,
TypeSerializer elementTypeSerializer, JsonSerializer<Object> elementValueSerializer)
throws JsonMappingException
{
// [databind#467]: This is where we could allow serialization "as POJO": But! It's
// nasty to undo, and does not apply on per-property basis. So, hardly optimal
JsonFormat.Value format = beanDesc.findExpectedFormat(null);
if ((format != null) && format.getShape() == JsonFormat.Shape.OBJECT) {
return null;
}
JsonSerializer<?> ser = null;
// Order of lookups:
// 1. Custom serializers
// 2. Annotations (@JsonValue, @JsonDeserialize)
// 3. Defaults
final SerializationConfig config = prov.getConfig();
for (Serializers serializers : customSerializers()) { // (1) Custom
ser = serializers.findMapSerializer(config, type, beanDesc,
keySerializer, elementTypeSerializer, elementValueSerializer);
if (ser != null) { break; }
}
if (ser == null) {
ser = findSerializerByAnnotations(prov, type, beanDesc); // (2) Annotations
if (ser == null) {
Object filterId = findFilterId(config, beanDesc);
// 01-May-2016, tatu: Which base type to use here gets tricky, since
// most often it ought to be `Map` or `EnumMap`, but due to abstract
// mapping it will more likely be concrete type like `HashMap`.
// So, for time being, just pass `Map.class`
JsonIgnoreProperties.Value ignorals = config.getDefaultPropertyIgnorals(Map.class,
beanDesc.getClassInfo());
Set<String> ignored = (ignorals == null) ? null
: ignorals.findIgnoredForSerialization();
MapSerializer mapSer = MapSerializer.construct(ignored,
type, staticTyping, elementTypeSerializer,
keySerializer, elementValueSerializer, filterId);
ser = _checkMapContentInclusion(prov, beanDesc, mapSer);
}
}
// [databind#120]: Allow post-processing
if (_factoryConfig.hasSerializerModifiers()) {
for (BeanSerializerModifier mod : _factoryConfig.serializerModifiers()) {
ser = mod.modifyMapSerializer(config, type, beanDesc, ser);
}
}
return ser;
}
@Override
public final JsonFormat.Value getDefaultPropertyFormat(Class<?> baseType) {
return _config.getDefaultPropertyFormat(baseType);
}
/**
* @since 2.9
*/
protected JsonSerializer<?> buildMapEntrySerializer(SerializerProvider prov,
JavaType type, BeanDescription beanDesc, boolean staticTyping,
JavaType keyType, JavaType valueType)
throws JsonMappingException
{
// [databind#865]: Allow serialization "as POJO" -- note: to undo, declare
// serialization as `Shape.NATURAL` instead; that's JSON Object too.
JsonFormat.Value formatOverride = prov.getDefaultPropertyFormat(Map.Entry.class);
JsonFormat.Value formatFromAnnotation = beanDesc.findExpectedFormat(null);
JsonFormat.Value format = JsonFormat.Value.merge(formatFromAnnotation, formatOverride);
if (format.getShape() == JsonFormat.Shape.OBJECT) {
return null;
}
MapEntrySerializer ser = new MapEntrySerializer(valueType, keyType, valueType,
staticTyping, createTypeSerializer(prov.getConfig(), valueType), null);
final JavaType contentType = ser.getContentType();
JsonInclude.Value inclV = _findInclusionWithContent(prov, beanDesc,
contentType, Map.Entry.class);
// Need to support global legacy setting, for now:
JsonInclude.Include incl = (inclV == null) ? JsonInclude.Include.USE_DEFAULTS : inclV.getContentInclusion();
if (incl == JsonInclude.Include.USE_DEFAULTS
|| incl == JsonInclude.Include.ALWAYS) {
return ser;
}
// NOTE: mostly copied from `PropertyBuilder`; would be nice to refactor
// but code is not identical nor are these types related
Object valueToSuppress;
boolean suppressNulls = true; // almost always, but possibly not with CUSTOM
switch (incl) {
case NON_DEFAULT:
valueToSuppress = BeanUtil.getDefaultValue(contentType);
if (valueToSuppress != null) {
if (valueToSuppress.getClass().isArray()) {
valueToSuppress = ArrayBuilders.getArrayComparator(valueToSuppress);
}
}
break;
case NON_ABSENT:
valueToSuppress = contentType.isReferenceType()
? MapSerializer.MARKER_FOR_EMPTY : null;
break;
case NON_EMPTY:
valueToSuppress = MapSerializer.MARKER_FOR_EMPTY;
break;
case CUSTOM:
valueToSuppress = prov.includeFilterInstance(null, inclV.getContentFilter());
if (valueToSuppress == null) { // is this legal?
suppressNulls = true;
} else {
suppressNulls = prov.includeFilterSuppressNulls(valueToSuppress);
}
break;
case NON_NULL:
default: // should not matter but...
valueToSuppress = null;
break;
}
return ser.withContentInclusion(valueToSuppress, suppressNulls);
}
/**
* Convenience method that is roughly equivalent to
*<pre>
* return intr.findFormat(getMember());
*</pre>
* and specifically does NOT try to find per-type format defaults to merge;
* use {@link #findPropertyFormat} if such defaults would be useful.
*
* @since 2.6
*
* @deprecated since 2.8 use {@link #findPropertyFormat} instead.
*/
@Deprecated
public JsonFormat.Value findFormatOverrides(AnnotationIntrospector intr);
/**
* Method for checking what is the expected format for POJO, as
* defined by defaults and possible annotations.
* Note that this may be further refined by per-property annotations.
*
* @since 2.1
*/
public abstract JsonFormat.Value findExpectedFormat(JsonFormat.Value defValue);