/** * Method called by {@link BeanDeserializerFactory} to see if there might be a standard * deserializer registered for given type. */ @SuppressWarnings("unchecked") protected JsonDeserializer<Object> findStdDeserializer( DeserializationConfig config, JavaType type) throws JsonMappingException { Class<?> cls = type.getRawClass(); // note: we do NOT check for custom deserializers here; that's for sub-class to do JsonDeserializer<Object> deser = _simpleDeserializers.get(new ClassKey(cls)); if (deser != null) { return deser; } // [JACKSON-283]: AtomicReference is a rather special type... if (AtomicReference.class.isAssignableFrom(cls)) { // Must find parameterization TypeFactory tf = config.getTypeFactory(); JavaType[] params = tf.findTypeParameters(type, AtomicReference.class); JavaType referencedType; if (params == null || params.length < 1) { // untyped (raw) referencedType = TypeFactory.unknownType(); } else { referencedType = params[0]; } JsonDeserializer<?> d2 = new JdkDeserializers.AtomicReferenceDeserializer(referencedType); return (JsonDeserializer<Object>) d2; } // [JACKSON-386]: External/optional type handlers are handled somewhat differently JsonDeserializer<?> d = optionalHandlers.findDeserializer(type, config); if (d != null) { return (JsonDeserializer<Object>) d; } return null; }
public JsonSerializer<?> findSerializer( SerializationConfig config, JavaType type, BeanDescription beanDesc) { final Class<?> rawType = type.getRawClass(); if (_jdk7Helper != null) { Class<?> path = _jdk7Helper.getClassJavaNioFilePath(); if (path.isAssignableFrom(rawType)) { return ToStringSerializer.instance; } } if ((CLASS_DOM_NODE != null) && CLASS_DOM_NODE.isAssignableFrom(rawType)) { return (JsonSerializer<?>) instantiate(SERIALIZER_FOR_DOM_NODE); } String className = rawType.getName(); String factoryName; if (className.startsWith(PACKAGE_PREFIX_JAVAX_XML) || hasSuperClassStartingWith(rawType, PACKAGE_PREFIX_JAVAX_XML)) { factoryName = SERIALIZERS_FOR_JAVAX_XML; } else { return null; } Object ob = instantiate(factoryName); if (ob == null) { // could warn, if we had logging system (j.u.l?) return null; } return ((Serializers) ob).findSerializer(config, type, beanDesc); }
/* * Enabled aggressive block sorting */ @Override public Collection<NamedType> collectAndResolveSubtypes(AnnotatedMember object, MapperConfig<?> mapperConfig, AnnotationIntrospector annotationIntrospector, JavaType javaType) { void var4_6; if (javaType == null) { Class class_ = object.getRawType(); } else { Class class_ = javaType.getRawClass(); } HashMap<NamedType, NamedType> hashMap = new HashMap<NamedType, NamedType>(); if (this._registeredSubtypes != null) { for (NamedType namedType : this._registeredSubtypes) { if (!var4_6.isAssignableFrom(namedType.getType())) continue; this._collectAndResolve(AnnotatedClass.constructWithoutSuperTypes(namedType.getType(), annotationIntrospector, mapperConfig), namedType, mapperConfig, annotationIntrospector, hashMap); } } if ((object = annotationIntrospector.findSubtypes((Annotated)object)) != null) { object = object.iterator(); while (object.hasNext()) { NamedType namedType = (NamedType)object.next(); this._collectAndResolve(AnnotatedClass.constructWithoutSuperTypes(namedType.getType(), annotationIntrospector, mapperConfig), namedType, mapperConfig, annotationIntrospector, hashMap); } } object = new NamedType(var4_6, null); this._collectAndResolve(AnnotatedClass.constructWithoutSuperTypes(var4_6, annotationIntrospector, mapperConfig), (NamedType)object, mapperConfig, annotationIntrospector, hashMap); return new ArrayList<NamedType>(hashMap.values()); }
@SuppressWarnings("unchecked") public static JsonSerializer<Object> getStdKeySerializer(JavaType keyType) { if (keyType == null) { return DEFAULT_KEY_SERIALIZER; } Class<?> cls = keyType.getRawClass(); if (cls == String.class) { return DEFAULT_STRING_SERIALIZER; } if (cls == Object.class || cls.isPrimitive() || Number.class.isAssignableFrom(cls)) { return DEFAULT_KEY_SERIALIZER; } if (Date.class.isAssignableFrom(cls)) { return (JsonSerializer<Object>) DateKeySerializer.instance; } if (Calendar.class.isAssignableFrom(cls)) { return (JsonSerializer<Object>) CalendarKeySerializer.instance; } /* 14-Mar-2014, tatu: Should support @JsonValue, as per #47; but that * requires extensive introspection, and passing in more information * to this method. */ // If no match, just use default one: return DEFAULT_KEY_SERIALIZER; }
public JsonDeserializer<?> findDeserializer( JavaType type, DeserializationConfig config, BeanDescription beanDesc) throws JsonMappingException { final Class<?> rawType = type.getRawClass(); if (_jdk7Helper != null) { JsonDeserializer<?> deser = _jdk7Helper.getDeserializerForJavaNioFilePath(rawType); if (deser != null) { return deser; } } if ((CLASS_DOM_NODE != null) && CLASS_DOM_NODE.isAssignableFrom(rawType)) { return (JsonDeserializer<?>) instantiate(DESERIALIZER_FOR_DOM_NODE); } if ((CLASS_DOM_DOCUMENT != null) && CLASS_DOM_DOCUMENT.isAssignableFrom(rawType)) { return (JsonDeserializer<?>) instantiate(DESERIALIZER_FOR_DOM_DOCUMENT); } String className = rawType.getName(); String factoryName; if (className.startsWith(PACKAGE_PREFIX_JAVAX_XML) || hasSuperClassStartingWith(rawType, PACKAGE_PREFIX_JAVAX_XML)) { factoryName = DESERIALIZERS_FOR_JAVAX_XML; } else { return null; } Object ob = instantiate(factoryName); if (ob == null) { // could warn, if we had logging system (j.u.l?) return null; } return ((Deserializers) ob).findBeanDeserializer(type, config, beanDesc); }
protected BeanPropertyWriter _constructVirtualProperty( JsonAppend.Prop prop, MapperConfig<?> config, AnnotatedClass ac) { PropertyMetadata metadata = prop.required() ? PropertyMetadata.STD_REQUIRED : PropertyMetadata.STD_OPTIONAL; PropertyName propName = _propertyName(prop.name(), prop.namespace()); JavaType type = config.constructType(prop.type()); // now, then, we need a placeholder for member (no real Field/Method): AnnotatedMember member = new VirtualAnnotatedMember( ac, ac.getRawType(), propName.getSimpleName(), type.getRawClass()); // and with that and property definition SimpleBeanPropertyDefinition propDef = SimpleBeanPropertyDefinition.construct(config, member, propName, metadata, prop.include()); Class<?> implClass = prop.value(); HandlerInstantiator hi = config.getHandlerInstantiator(); VirtualBeanPropertyWriter bpw = (hi == null) ? null : hi.virtualPropertyWriterInstance(config, implClass); if (bpw == null) { bpw = (VirtualBeanPropertyWriter) ClassUtil.createInstance(implClass, config.canOverrideAccessModifiers()); } // one more thing: give it necessary contextual information return bpw.withConfig(config, ac, propDef, type); }
public ValueInstantiator constructValueInstantiator(DeserializationConfig config) { JavaType delegateType; boolean maybeVanilla = !_hasNonDefaultCreator; if (maybeVanilla || (_creators[C_DELEGATE] == null)) { delegateType = null; } else { // need to find type... int ix = 0; if (_delegateArgs != null) { for (int i = 0, len = _delegateArgs.length; i < len; ++i) { if (_delegateArgs[i] == null) { // marker for delegate itself ix = i; break; } } } delegateType = _creators[C_DELEGATE].getParameterType(ix); } final JavaType type = _beanDesc.getType(); // Any non-standard creator will prevent; with one exception: int-valued constructor // that standard containers have can be ignored maybeVanilla &= !_hasNonDefaultCreator; if (maybeVanilla) { /* 10-May-2014, tatu: If we have nothing special, and we are dealing with one * of "well-known" types, can create a non-reflection-based instantiator. */ final Class<?> rawType = type.getRawClass(); if (rawType == Collection.class || rawType == List.class || rawType == ArrayList.class) { return new Vanilla(Vanilla.TYPE_COLLECTION); } if (rawType == Map.class || rawType == LinkedHashMap.class) { return new Vanilla(Vanilla.TYPE_MAP); } if (rawType == HashMap.class) { return new Vanilla(Vanilla.TYPE_HASH_MAP); } } StdValueInstantiator inst = new StdValueInstantiator(config, type); inst.configureFromObjectSettings( _creators[C_DEFAULT], _creators[C_DELEGATE], delegateType, _delegateArgs, _creators[C_PROPS], _propertyBasedArgs); inst.configureFromStringCreator(_creators[C_STRING]); inst.configureFromIntCreator(_creators[C_INT]); inst.configureFromLongCreator(_creators[C_LONG]); inst.configureFromDoubleCreator(_creators[C_DOUBLE]); inst.configureFromBooleanCreator(_creators[C_BOOLEAN]); inst.configureIncompleteParameter(_incompleteParameter); return inst; }
@Override public JavaType widenContentsBy(Class<?> contentClass) { // Can do a quick check first: if (contentClass == _elementType.getRawClass()) { return this; } return new CollectionLikeType( _class, _elementType.widenBy(contentClass), _valueHandler, _typeHandler); }
@Override public KeyDeserializer findKeyDeserializer( JavaType type, DeserializationConfig config, BeanDescription beanDesc) throws JsonMappingException { final Class<?> candidateTT = type.getRawClass(); if (MetaTinyTypes.isTinyType(candidateTT)) { return new TinyTypesKeyDeserializer(candidateTT); } return null; }
protected JsonDeserializer<Object> _handleUnknownValueDeserializer(JavaType type) throws JsonMappingException { /* Let's try to figure out the reason, to give better error * messages */ Class<?> rawClass = type.getRawClass(); if (!ClassUtil.isConcrete(rawClass)) { throw new JsonMappingException("Can not find a Value deserializer for abstract type " + type); } throw new JsonMappingException("Can not find a Value deserializer for type " + type); }
// [databind#938] public void testRecursivePair() throws Exception { JavaType t = MAPPER.constructType(ImmutablePair.class); assertNotNull(t); assertEquals(ImmutablePair.class, t.getRawClass()); List<ImmutablePair<String, Double>> list = new ArrayList<ImmutablePair<String, Double>>(); list.add(ImmutablePair.of("Hello World!", 123d)); String json = MAPPER.writeValueAsString(list); assertNotNull(json); // can not deserialize with current definition, however }
protected MinimalClassNameIdResolver(JavaType javatype, TypeFactory typefactory) { super(javatype, typefactory); javatype = javatype.getRawClass().getName(); int i = javatype.lastIndexOf('.'); if (i < 0) { _basePackageName = ""; _basePackagePrefix = "."; return; } else { _basePackagePrefix = javatype.substring(0, i + 1); _basePackageName = javatype.substring(0, i); return; } }
@Override public JavaType modifyType( JavaType type, Type jdkType, TypeBindings bindings, TypeFactory typeFactory) { final Class<?> raw = type.getRawClass(); if (Seq.class.isAssignableFrom(raw) && CharSeq.class != raw) { return CollectionLikeType.construct(raw, type.containedTypeOrUnknown(0)); } if (Set.class.isAssignableFrom(raw)) { return CollectionLikeType.construct(raw, type.containedTypeOrUnknown(0)); } if (PriorityQueue.class.isAssignableFrom(raw)) { return CollectionLikeType.construct(raw, type.containedTypeOrUnknown(0)); } return type; }
/** * Helper method used for figuring out if given raw type is a collection ("indexed") type; in * which case a wrapper element is typically added. */ public static boolean isIndexedType(JavaType type) { if (type.isContainerType()) { Class<?> cls = type.getRawClass(); // One special case; byte[] will be serialized as base64-encoded String, not real array, so: // (actually, ditto for char[]; thought to be a String) if (cls == byte[].class || cls == char[].class) { return false; } // issue#5: also, should not add wrapping for Maps if (Map.class.isAssignableFrom(cls)) { return false; } return true; } return false; }
private ObjBase getValue(Object valueId, JavaType type) { ObjectId id; try { id = new ObjectId(valueId); } catch (IllegalArgumentException e) { // TODO: collect these and similar warnings and send them to user output also log.warn("{} is an invalid ObjectId", valueId); return null; } DBObject result = query(id); if (result == null) { log.warn("Could not find {} in database", id); return null; } return makeValue(id, result, (Class<? extends ObjBase>) type.getRawClass()); }
/** * Method that {@link DeserializerCache}s call to create a new deserializer for types other than * Collections, Maps, arrays and enums. */ @Override public JsonDeserializer<Object> createBeanDeserializer( DeserializationContext ctxt, JavaType type, BeanDescription beanDesc) throws JsonMappingException { final DeserializationConfig config = ctxt.getConfig(); // We may also have custom overrides: JsonDeserializer<Object> custom = _findCustomBeanDeserializer(type, config, beanDesc); if (custom != null) { return custom; } /* One more thing to check: do we have an exception type * (Throwable or its sub-classes)? If so, need slightly * different handling. */ if (type.isThrowable()) { return buildThrowableDeserializer(ctxt, type, beanDesc); } /* Or, for abstract types, may have alternate means for resolution * (defaulting, materialization) */ if (type.isAbstract()) { // [JACKSON-41] (v1.6): Let's make it possible to materialize abstract types. JavaType concreteType = materializeAbstractType(config, beanDesc); if (concreteType != null) { /* important: introspect actual implementation (abstract class or * interface doesn't have constructors, for one) */ beanDesc = config.introspect(concreteType); return buildBeanDeserializer(ctxt, concreteType, beanDesc); } } // Otherwise, may want to check handlers for standard types, from superclass: JsonDeserializer<Object> deser = findStdDeserializer(config, type); if (deser != null) { return deser; } // Otherwise: could the class be a Bean class? If not, bail out if (!isPotentialBeanType(type.getRawClass())) { return null; } // Use generic bean introspection to build deserializer return buildBeanDeserializer(ctxt, type, beanDesc); }
protected JsonDeserializer<?> _createDeserializer2( DeserializationContext ctxt, DeserializerFactory factory, JavaType type, BeanDescription beanDesc) throws JsonMappingException { final DeserializationConfig config = ctxt.getConfig(); // If not, let's see which factory method to use: if (type.isEnumType()) { return factory.createEnumDeserializer(ctxt, type, beanDesc); } if (type.isContainerType()) { if (type.isArrayType()) { return factory.createArrayDeserializer(ctxt, (ArrayType) type, beanDesc); } if (type.isMapLikeType()) { MapLikeType mlt = (MapLikeType) type; if (mlt.isTrueMapType()) { return factory.createMapDeserializer(ctxt, (MapType) mlt, beanDesc); } return factory.createMapLikeDeserializer(ctxt, mlt, beanDesc); } if (type.isCollectionLikeType()) { /* 03-Aug-2012, tatu: As per [Issue#40], one exception is if shape * is to be Shape.OBJECT. Ideally we'd determine it bit later on * (to allow custom handler checks), but that won't work for other * reasons. So do it here. */ JsonFormat.Value format = beanDesc.findExpectedFormat(null); if (format == null || format.getShape() != JsonFormat.Shape.OBJECT) { CollectionLikeType clt = (CollectionLikeType) type; if (clt.isTrueCollectionType()) { return factory.createCollectionDeserializer(ctxt, (CollectionType) clt, beanDesc); } return factory.createCollectionLikeDeserializer(ctxt, clt, beanDesc); } } } if (JsonNode.class.isAssignableFrom(type.getRawClass())) { return factory.createTreeDeserializer(config, type, beanDesc); } return factory.createBeanDeserializer(ctxt, type, beanDesc); }
/** * Helper method called when current token is no START_ARRAY. Will either throw an exception, or * try to handle value as if member of implicit array, depending on configuration. */ private final Collection<String> handleNonArray( JsonParser jp, DeserializationContext ctxt, Collection<String> result) throws IOException { // [JACKSON-526]: implicit arrays from single values? if (!ctxt.isEnabled(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)) { throw ctxt.mappingException(_collectionType.getRawClass()); } // Strings are one of "native" (intrinsic) types, so there's never type deserializer involved JsonDeserializer<String> valueDes = _valueDeserializer; JsonToken t = jp.getCurrentToken(); String value; if (t == JsonToken.VALUE_NULL) { value = (valueDes == null) ? null : valueDes.getNullValue(); } else { value = (valueDes == null) ? _parseString(jp, ctxt) : valueDes.deserialize(jp, ctxt); } result.add(value); return result; }
protected BeanPropertyWriter _constructVirtualProperty( JsonAppend.Attr attr, MapperConfig<?> config, AnnotatedClass ac, JavaType type) { PropertyMetadata metadata = attr.required() ? PropertyMetadata.STD_REQUIRED : PropertyMetadata.STD_OPTIONAL; // could add Index, Description in future, if those matter String attrName = attr.value(); // allow explicit renaming; if none, default to attribute name PropertyName propName = _propertyName(attr.propName(), attr.propNamespace()); if (!propName.hasSimpleName()) { propName = PropertyName.construct(attrName); } // now, then, we need a placeholder for member (no real Field/Method): AnnotatedMember member = new VirtualAnnotatedMember(ac, ac.getRawType(), attrName, type.getRawClass()); // and with that and property definition SimpleBeanPropertyDefinition propDef = SimpleBeanPropertyDefinition.construct(config, member, propName, metadata, attr.include()); // can construct the property writer return AttributePropertyWriter.construct(attrName, propDef, ac.getAnnotations(), type); }
/** * The method to be called by {@link ObjectWriter} for serializing given value (assumed to be of * specified root type, instead of runtime type of value), when it may know specific {@link * JsonSerializer} to use. * * @param rootType Type to use for locating serializer to use, instead of actual runtime type, if * no serializer is passed * @param ser Root Serializer to use, if not null * @since 2.1 */ public void serializeValue( JsonGenerator jgen, Object value, JavaType rootType, JsonSerializer<Object> ser) throws IOException, JsonGenerationException { final boolean wrap; if (value == null) { ser = getDefaultNullValueSerializer(); wrap = false; } else { // Let's ensure types are compatible at this point if (rootType != null) { if (!rootType.getRawClass().isAssignableFrom(value.getClass())) { _reportIncompatibleRootType(value, rootType); } } // root value, not reached via property: if (ser == null) { ser = findTypedValueSerializer(rootType, true, null); } wrap = _config.isEnabled(SerializationFeature.WRAP_ROOT_VALUE); if (wrap) { jgen.writeStartObject(); jgen.writeFieldName(_rootNames.findRootName(rootType, _config)); } } try { ser.serialize(value, jgen, this); if (wrap) { jgen.writeEndObject(); } } catch (IOException ioe) { // no wrapping for IO (and derived) throw ioe; } catch (Exception e) { // but others do need to be, to get path etc String msg = e.getMessage(); if (msg == null) { msg = "[no message for " + e.getClass().getName() + "]"; } throw new JsonMappingException(msg, e); } }
/** @since 2.8 */ public static MapSerializer construct( Set<String> ignoredEntries, JavaType mapType, boolean staticValueType, TypeSerializer vts, JsonSerializer<Object> keySerializer, JsonSerializer<Object> valueSerializer, Object filterId) { JavaType keyType, valueType; if (mapType == null) { keyType = valueType = UNSPECIFIED_TYPE; } else { keyType = mapType.getKeyType(); valueType = mapType.getContentType(); } // If value type is final, it's same as forcing static value typing: if (!staticValueType) { staticValueType = (valueType != null && valueType.isFinal()); } else { // also: Object.class can not be handled as static, ever if (valueType.getRawClass() == Object.class) { staticValueType = false; } } MapSerializer ser = new MapSerializer( ignoredEntries, keyType, valueType, staticValueType, vts, keySerializer, valueSerializer); if (filterId != null) { ser = ser.withFilterId(filterId); } return ser; }
@Override public Object findInjectableValue( Object valueId, DeserializationContext ctxt, BeanProperty forProperty, Object beanInstance) { // if a container, get content type JavaType type = forProperty.getType(); if (type.isCollectionLikeType() | type.isArrayType()) { type = type.getContentType(); } // checking annotation catches properties with interface types if (ObjBase.class.isAssignableFrom(type.getRawClass()) || forProperty.getMember().getAnnotated().isAnnotationPresent(Reference.class)) { try { return super.findInjectableValue(valueId, ctxt, forProperty, beanInstance); } catch (IllegalArgumentException e) { Object value = getValue(valueId, type); return value; } } else { return super.findInjectableValue(valueId, ctxt, forProperty, beanInstance); } }