/** * Constructs the object based on the content as a List, the JSON can be an array or just a single value without the [] symbols * @param content Reader * @return A collection of the specified type * @throws IOException */ public <T> List<T> constructList(Reader content, Class<T> requiredType) throws IOException, JsonMappingException, JsonParseException { ObjectReader reader = objectMapper.reader(TypeFactory.defaultInstance().constructParametricType(List.class, requiredType)); try { List<T> toReturn = reader.readValue(content); if (toReturn == null || toReturn.isEmpty()) { throw new InvalidArgumentException("Could not read content from HTTP request body, the list is empty"); } return toReturn; } catch (IOException error) { throw new InvalidArgumentException("Could not read content from HTTP request body: "+error.getMessage()); } }
/** * Determine a Jackson JavaType for the given JMS Message, * typically parsing a type id message property. * <p>The default implementation parses the configured type id property name * and consults the configured type id mapping. This can be overridden with * a different strategy, e.g. doing some heuristics based on message origin. * @param message the JMS Message to set the type id on * @throws JMSException if thrown by JMS methods * @see #setTypeIdOnMessage(Object, javax.jms.Message) * @see #setTypeIdPropertyName(String) * @see #setTypeIdMappings(java.util.Map) */ protected JavaType getJavaTypeForMessage(Message message) throws JMSException { String typeId = message.getStringProperty(this.typeIdPropertyName); if (typeId == null) { throw new MessageConversionException("Could not find type id property [" + this.typeIdPropertyName + "]"); } Class<?> mappedClass = this.idClassMappings.get(typeId); if (mappedClass != null) { return TypeFactory.type(mappedClass); } try { Class<?> typeClass = ClassUtils.forName(typeId, this.beanClassLoader); return TypeFactory.type(typeClass); } catch (Throwable ex) { throw new MessageConversionException("Failed to resolve type id [" + typeId + "]", ex); } }
public JavaType typeFromId(String paramString) { if (paramString.indexOf('<') > 0) return TypeFactory.fromCanonical(paramString); try { Class localClass = Class.forName(paramString, true, Thread.currentThread().getContextClassLoader()); JavaType localJavaType = this._typeFactory.constructSpecializedType(this._baseType, localClass); return localJavaType; } catch (ClassNotFoundException localClassNotFoundException) { throw new IllegalArgumentException("Invalid type id '" + paramString + "' (for id type 'Id.class'): no such class found"); } catch (Exception localException) { } throw new IllegalArgumentException("Invalid type id '" + paramString + "' (for id type 'Id.class'): " + localException.getMessage(), localException); }
protected JavaType getType(TypeBindings paramTypeBindings, TypeVariable<?>[] paramArrayOfTypeVariable) { if ((paramArrayOfTypeVariable != null) && (paramArrayOfTypeVariable.length > 0)) { paramTypeBindings = paramTypeBindings.childInstance(); int i = paramArrayOfTypeVariable.length; int j = 0; if (j < i) { TypeVariable<?> localTypeVariable = paramArrayOfTypeVariable[j]; paramTypeBindings._addPlaceholder(localTypeVariable.getName()); Type localType = localTypeVariable.getBounds()[0]; if (localType == null); for (JavaType localJavaType = TypeFactory.unknownType(); ; localJavaType = paramTypeBindings.resolveType(localType)) { paramTypeBindings.addBinding(localTypeVariable.getName(), localJavaType); j++; break; } } } return paramTypeBindings.resolveType(getGenericType()); }
protected JsonDeserializer<Object> findStdBeanDeserializer(DeserializationConfig paramDeserializationConfig, DeserializerProvider paramDeserializerProvider, JavaType paramJavaType, BeanProperty paramBeanProperty) throws JsonMappingException { JsonDeserializer localJsonDeserializer1 = (JsonDeserializer)_simpleDeserializers.get(paramJavaType); if (localJsonDeserializer1 != null) return localJsonDeserializer1; if (AtomicReference.class.isAssignableFrom(paramJavaType.getRawClass())) { JavaType[] arrayOfJavaType = paramDeserializationConfig.getTypeFactory().findTypeParameters(paramJavaType, AtomicReference.class); if ((arrayOfJavaType == null) || (arrayOfJavaType.length < 1)); for (JavaType localJavaType = TypeFactory.unknownType(); ; localJavaType = arrayOfJavaType[0]) return new StdDeserializer.AtomicReferenceDeserializer(localJavaType, paramBeanProperty); } JsonDeserializer localJsonDeserializer2 = this.optionalHandlers.findDeserializer(paramJavaType, paramDeserializationConfig, paramDeserializerProvider); if (localJsonDeserializer2 != null) return localJsonDeserializer2; return null; }
public JsonNode getSchema(SerializerProvider provider, Type typeHint) throws JsonMappingException { ObjectNode o = createSchemaNode("array", true); if (typeHint != null) { JavaType javaType = TypeFactory.type(typeHint); if (javaType.isArrayType()) { Class<?> componentType = ((ArrayType) javaType).getContentType().getRawClass(); JsonSerializer<Object> ser = provider.findValueSerializer(componentType); JsonNode schemaNode = (ser instanceof SchemaAware) ? ((SchemaAware) ser).getSchema(provider, null) : JsonSchema.getDefaultSchemaNode(); o.put("items", schemaNode); } } return o; }
/** * We can try to find the actual serializer for value, if we can * statically figure out what the result type must be. */ public void resolve(SerializerProvider provider) throws JsonMappingException { if (_valueSerializer == null) { /* Note: we can only assign serializer statically if the * declared type is final -- if not, we don't really know * the actual type until we get the instance. */ // 10-Mar-2010, tatu: Except if static typing is to be used if (provider.isEnabled(SerializationConfig.Feature.USE_STATIC_TYPING) || Modifier.isFinal(_accessorMethod.getReturnType().getModifiers())) { JavaType t = TypeFactory.type(_accessorMethod.getGenericReturnType()); // false -> no need to cache /* 10-Mar-2010, tatu: Ideally we would actually separate out type * serializer from value serializer; but, alas, there's no access * to serializer factory at this point... */ _valueSerializer = provider.findTypedValueSerializer(t, false); } } }
/** * Factory method used to construct Map serializers. * * @param ignoredList Array of entry names that are to be filtered on * serialization; null if none * @param mapType Declared type information (needed for static typing) * @param staticValueType Whether static typing should be used for the * Map (which includes its contents) * @param vts Type serializer to use for map entry values, if any */ public static MapSerializer construct(String[] ignoredList, JavaType mapType, boolean staticValueType, TypeSerializer vts) { HashSet<String> ignoredEntries = toSet(ignoredList); JavaType valueType = (mapType == null) ? TypeFactory.type(Object.class) : mapType.getContentType(); // If value type is final, it's same as forcing static value typing: if (!staticValueType) { staticValueType = (valueType != null && valueType.isFinal()); } /* for plain vanilla case can return singleton; plain meaning that there are * no ignored entries (no view), non-static type (can not statically determine * value serializer) and no assigned value type serializer. */ if (!staticValueType && (ignoredEntries == null) && (vts == null)) { return instance; } return new MapSerializer(ignoredEntries, valueType, staticValueType, vts); }
/** * Method that will try to construct a value serializer; and if * one is succesfully created, cache it for reuse. */ protected JsonSerializer<Object> _createAndCacheUntypedSerializer(Class<?> type) throws JsonMappingException { JsonSerializer<Object> ser; try { ser = _createUntypedSerializer(TypeFactory.type(type)); } catch (IllegalArgumentException iae) { /* We better only expose checked exceptions, since those * are what caller is expected to handle */ throw new JsonMappingException(iae.getMessage(), null, iae); } if (ser != null) { _serializerCache.addNonTypedSerializer(type, ser); /* Finally: some serializers want to do post-processing, after * getting registered (to handle cyclic deps). */ if (ser instanceof ResolvableSerializer) { _resolveSerializer((ResolvableSerializer)ser); } } return ser; }
@Override public JsonNode getSchema(SerializerProvider provider, Type typeHint) throws JsonMappingException { ObjectNode objectNode = createSchemaNode("string", true); if (typeHint != null) { JavaType type = TypeFactory.type(typeHint); if (type.isEnumType()) { ArrayNode enumNode = objectNode.putArray("enum"); for (String value : _values.values()) { enumNode.add(value); } } } return objectNode; }
/** * Method that will try to determine statically defined type of property * being serialized, based on annotations (for overrides), and alternatively * declared type (if static typing for serialization is enabled). * If neither can be used (no annotations, dynamic typing), returns null. */ protected JavaType findSerializationType(Annotated a, boolean useStaticTyping) { // [JACKSON-120]: Check to see if serialization type is fixed Class<?> serializationType = _annotationIntrospector.findSerializationType(a); if (serializationType != null) { // Must be a super type... Class<?> raw = a.getRawType(); if (!serializationType.isAssignableFrom(raw)) { throw new IllegalArgumentException("Illegal concrete-type annotation for method '"+a.getName()+"': class "+serializationType.getName()+" not a super-type of (declared) class "+raw.getName()); } return TypeFactory.type(serializationType); } /* [JACKSON-114]: if using static typing, declared type is known * to be the type... */ JsonSerialize.Typing typing = _annotationIntrospector.findSerializationTyping(a); if (typing != null) { useStaticTyping = (typing == JsonSerialize.Typing.STATIC); } if (useStaticTyping) { return TypeFactory.type(a.getGenericType()); } return null; }
@SuppressWarnings("unchecked") @Override public JsonNode getSchema(SerializerProvider provider, Type typeHint) throws JsonMappingException { ObjectNode o = createSchemaNode("object", true); if (typeHint instanceof ParameterizedType) { Type[] typeArgs = ((ParameterizedType) typeHint).getActualTypeArguments(); if (typeArgs.length == 2) { JavaType enumType = TypeFactory.type(typeArgs[0]); JavaType valueType = TypeFactory.type(typeArgs[1]); ObjectNode propsNode = JsonNodeFactory.instance.objectNode(); Class<Enum<?>> enumClass = (Class<Enum<?>>) enumType.getRawClass(); for (Enum<?> enumValue : enumClass.getEnumConstants()) { JsonSerializer<Object> ser = provider.findValueSerializer(valueType.getRawClass()); JsonNode schemaNode = (ser instanceof SchemaAware) ? ((SchemaAware) ser).getSchema(provider, null) : JsonSchema.getDefaultSchemaNode(); propsNode.put(provider.getConfig().getAnnotationIntrospector().findEnumValue((Enum<?>)enumValue), schemaNode); } o.put("properties", propsNode); } } return o; }
public BasicBeanDescription forSerialization(SerializationConfig cfg, Class<?> c, MixInResolver r) { AnnotationIntrospector ai = cfg.getAnnotationIntrospector(); AnnotatedClass ac = AnnotatedClass.construct(c, ai, r); // False -> no need to collect ignorable member list ac.resolveMemberMethods(getSerializationMethodFilter(cfg), false); /* only the default constructor needed here (that's needed * in case we need to check default bean property values, * to omit them) */ /* 31-Oct-2009, tatus: Actually, creator info will come in handy * for resolving [JACKSON-170] as well */ ac.resolveCreators(true); // False -> no need to collect ignorable field list ac.resolveFields(false); return new BasicBeanDescription(TypeFactory.type(c), ac, ai); }
public JavaType typeFromId(String paramString) { if (paramString.indexOf('<') > 0) return TypeFactory.fromCanonical(paramString); try { Class localClass = Class.forName(paramString, true, Thread.currentThread().getContextClassLoader()); JavaType localJavaType = this._typeFactory.constructSpecializedType(this._baseType, localClass); return localJavaType; } catch (ClassNotFoundException localClassNotFoundException) { throw new IllegalArgumentException("Invalid type id '" + paramString + "' (for id type 'Id.class'): no such class found"); } catch (Exception localException) { throw new IllegalArgumentException("Invalid type id '" + paramString + "' (for id type 'Id.class'): " + localException.getMessage(), localException); } }
protected JsonDeserializer<Object> findStdBeanDeserializer(DeserializationConfig paramDeserializationConfig, DeserializerProvider paramDeserializerProvider, JavaType paramJavaType, BeanProperty paramBeanProperty) { Class localClass = paramJavaType.getRawClass(); JsonDeserializer localJsonDeserializer = (JsonDeserializer)_simpleDeserializers.get(new ClassKey(localClass)); if (localJsonDeserializer != null); do { return localJsonDeserializer; if (AtomicReference.class.isAssignableFrom(localClass)) { JavaType[] arrayOfJavaType = paramDeserializationConfig.getTypeFactory().findTypeParameters(paramJavaType, AtomicReference.class); if ((arrayOfJavaType == null) || (arrayOfJavaType.length <= 0)); for (JavaType localJavaType = TypeFactory.unknownType(); ; localJavaType = arrayOfJavaType[0]) return new AtomicReferenceDeserializer(localJavaType, paramBeanProperty); } localJsonDeserializer = this.optionalHandlers.findDeserializer(paramJavaType, paramDeserializationConfig, paramDeserializerProvider); } while (localJsonDeserializer != null); return null; }
public static <T> ArrayList<T> toList(String jsonString, final Class<T> type) { try { return om.readValue(jsonString, TypeFactory.defaultInstance().constructCollectionType(ArrayList.class, type)); } catch (IOException e) { return null; } }
public static <T> ArrayList<T> toList(JsonNode jsonNode, final Class<T> type) { try { return om.readValue(jsonNode, TypeFactory.defaultInstance().constructCollectionType(ArrayList.class, type)); } catch (IOException e) { return null; } }
@SuppressWarnings("unchecked") private Collection<Object> deserializeValues(final JsonParser jp, final ObjectMapper codec) throws IOException { final TypeFactory typeFactory = codec.getTypeFactory(); final JavaType parameterizedType = typeFactory.constructCollectionType(List.class, collectionType.containedType(0)); return (Collection<Object>) codec.readValue(jp, parameterizedType); }
public MetricRestServlet(MetricsService service) { super(); metricService = service; stats = new ServletStats(); counterResultWriter = new ObjectMapper().typedWriter(TypeFactory.collectionType(List.class, Counter.class)); metricResultWriter = new ObjectMapper().typedWriter(TypeFactory.collectionType(List.class, RawNumericMetric.class)); }
@Override public <T> List<T> toJavaList(String json, Class<T> elementClass) { try { JavaType type = TypeFactory.collectionType(ArrayList.class, elementClass); return mapper.readValue(json, type); } catch (IOException e) { throw new FacebookJsonMappingException("Problem creating java object from json", e); } }
@SuppressWarnings("unchecked") public StdEscapeHTMLSerializerProvider(SerializationConfig serializationConfig) throws JsonMappingException { super(serializationConfig, new StdSerializerProvider(), BeanSerializerFactory.instance); JsonSerializer stringEscapeHTMLSerializer = new StringEscapeHTMLSerializer(); _serializerCache.addAndResolveNonTypedSerializer(String.class, stringEscapeHTMLSerializer, this); JavaType javaType = TypeFactory.fromCanonical(String.class.getName()); _serializerCache.addAndResolveNonTypedSerializer(javaType, stringEscapeHTMLSerializer, this); }
/** * Takes a JSON string and attempts to "map" it to the given class. It assumes the JSON * string is valid, and that it maps to the object you've indicated. If you want to run outside of "strict" mode, * pass false for the failOnUnknownProperties flag * @param jsonObjectClass The Class you wish to map the contents to * @param json The JSON you wish to map to the given Class * @param failOnUnknownProperties Whether or not to throw an exception if an unknown JSON attribute is encountered * @return An instance of the given Class, based on the attributes of the given JSON */ public static <T> T getMappedJsonObject( Class<T> jsonObjectClass, String json, boolean failOnUnknownProperties ) { TypeFactory t = TypeFactory.defaultInstance(); ObjectMapper mapper = new ObjectMapper(); mapper.configure( DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, failOnUnknownProperties ); T mappedObject; try { mappedObject = mapper.readValue( json, t.constructType( jsonObjectClass ) ); } catch ( Exception e ) { throw new RuntimeException( "Could not instantiate object of class [" + jsonObjectClass.getName()+ "]: " + e ); } return mappedObject; }
/** * Returns a list of objects of the specified type. If you send "false" in the 3rd parameter, it will be * forgiving of JSON properties that are not defined or inaccessible in the specified jsonObjectClass * @param jsonObjectClass The Class you wish to map the json to * @param json The JSON you wish to map to the given Class * @param failOnUnknownProperties Whether or not to throw an exception if an unknown JSON attribute is encountered * @return An instance of the given Class, based on the attributes of the given JSON */ public static <T> List<T> getMappedJsonObjectList(Class<T> jsonObjectClass, String json, boolean failOnUnknownProperties) { List<T> list; ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, failOnUnknownProperties); TypeFactory t = TypeFactory.defaultInstance(); try { list = mapper.readValue(json, t.constructCollectionType(ArrayList.class, jsonObjectClass)); return list; } catch (Exception ex) { ex.printStackTrace(); } throw new RuntimeException("Could not process JSON"); }
private <T> List<T> getAllValues(String rootUrl, int pageLen, Class<T> cls) { List<T> values = new ArrayList<T>(); try { String url = rootUrl + "?pagelen=" + pageLen; do { final JavaType type = TypeFactory.defaultInstance().constructParametricType(Pullrequest.Response.class, cls); Pullrequest.Response<T> response = parse(get(url), type); values.addAll(response.getValues()); url = response.getNext(); } while (url != null); } catch (Exception e) { logger.log(Level.WARNING, "invalid response.", e); } return values; }
@Test @SuppressWarnings("unchecked") public void readGenerics() throws IOException { MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter() { @Override protected JavaType getJavaType(Type type, Class<?> contextClass) { if (type instanceof Class && List.class.isAssignableFrom((Class<?>)type)) { return TypeFactory.collectionType(ArrayList.class, MyBean.class); } else { return super.getJavaType(type, contextClass); } } }; String body = "[{\"bytes\":\"AQI=\",\"array\":[\"Foo\",\"Bar\"],\"number\":42,\"string\":\"Foo\",\"bool\":true,\"fraction\":42.0}]"; MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8")); inputMessage.getHeaders().setContentType(new MediaType("application", "json")); List<MyBean> results = (List<MyBean>) converter.read(List.class, inputMessage); assertEquals(1, results.size()); MyBean result = results.get(0); assertEquals("Foo", result.getString()); assertEquals(42, result.getNumber()); assertEquals(42F, result.getFraction(), 0F); assertArrayEquals(new String[]{"Foo", "Bar"}, result.getArray()); assertTrue(result.isBool()); assertArrayEquals(new byte[]{0x1, 0x2}, result.getBytes()); }
public static KafkaCheckpoint deserialize(InputStream inputStream) throws IOException { TypeFactory typeFactory = _mapper.getTypeFactory(); MapType mapType = typeFactory.constructMapType(HashMap.class, Integer.class, Long.class); HashMap<Integer, Long> checkpoint = _mapper.readValue(inputStream, mapType); return new KafkaCheckpoint(checkpoint); }
private Map<String, JobConfig.Builder> getJobConfigs(ArrayNode root) throws HelixException, IOException { Map<String, JobConfig.Builder> jobConfigsMap = new HashMap<>(); for (Iterator<JsonNode> it = root.getElements(); it.hasNext(); ) { JsonNode job = it.next(); ZNRecord record = null; try { record = toZNRecord(job.toString()); } catch (IOException e) { // Ignore the parse since it could be just simple fields } if (record == null || record.getSimpleFields().isEmpty()) { Map<String, String> cfgMap = OBJECT_MAPPER.readValue(job.toString(), TypeFactory.defaultInstance() .constructMapType(HashMap.class, String.class, String.class)); jobConfigsMap .put(job.get(Properties.id.name()).getTextValue(), JobAccessor.getJobConfig(cfgMap)); } else { jobConfigsMap .put(job.get(Properties.id.name()).getTextValue(), JobAccessor.getJobConfig(record)); } } return jobConfigsMap; }
protected MinimalClassNameIdResolver(JavaType paramJavaType, TypeFactory paramTypeFactory) { super(paramJavaType, paramTypeFactory); String str = paramJavaType.getRawClass().getName(); int i = str.lastIndexOf('.'); if (i < 0) { this._basePackageName = ""; this._basePackagePrefix = "."; return; } this._basePackagePrefix = str.substring(0, i + 1); this._basePackageName = str.substring(0, i); }
protected JsonSerializer<?> buildIterableSerializer(SerializationConfig paramSerializationConfig, JavaType paramJavaType, BasicBeanDescription paramBasicBeanDescription, BeanProperty paramBeanProperty, boolean paramBoolean) { JavaType localJavaType = paramJavaType.containedType(0); if (localJavaType == null) localJavaType = TypeFactory.unknownType(); TypeSerializer localTypeSerializer = createTypeSerializer(paramSerializationConfig, localJavaType, paramBeanProperty); return ContainerSerializers.iterableSerializer(localJavaType, usesStaticTyping(paramSerializationConfig, paramBasicBeanDescription, localTypeSerializer, paramBeanProperty), localTypeSerializer, paramBeanProperty); }
protected JsonSerializer<?> buildIteratorSerializer(SerializationConfig paramSerializationConfig, JavaType paramJavaType, BasicBeanDescription paramBasicBeanDescription, BeanProperty paramBeanProperty, boolean paramBoolean) { JavaType localJavaType = paramJavaType.containedType(0); if (localJavaType == null) localJavaType = TypeFactory.unknownType(); TypeSerializer localTypeSerializer = createTypeSerializer(paramSerializationConfig, localJavaType, paramBeanProperty); return ContainerSerializers.iteratorSerializer(localJavaType, usesStaticTyping(paramSerializationConfig, paramBasicBeanDescription, localTypeSerializer, paramBeanProperty), localTypeSerializer, paramBeanProperty); }
public ObjectMapper setTypeFactory(TypeFactory paramTypeFactory) { this._typeFactory = paramTypeFactory; this._deserializationConfig = this._deserializationConfig.withTypeFactory(paramTypeFactory); this._serializationConfig = this._serializationConfig.withTypeFactory(paramTypeFactory); return this; }
public Base(ClassIntrospector<? extends BeanDescription> paramClassIntrospector, AnnotationIntrospector paramAnnotationIntrospector, VisibilityChecker<?> paramVisibilityChecker, PropertyNamingStrategy paramPropertyNamingStrategy, TypeFactory paramTypeFactory, TypeResolverBuilder<?> paramTypeResolverBuilder, DateFormat paramDateFormat, HandlerInstantiator paramHandlerInstantiator) { this._classIntrospector = paramClassIntrospector; this._annotationIntrospector = paramAnnotationIntrospector; this._visibilityChecker = paramVisibilityChecker; this._propertyNamingStrategy = paramPropertyNamingStrategy; this._typeFactory = paramTypeFactory; this._typeResolverBuilder = paramTypeResolverBuilder; this._dateFormat = paramDateFormat; this._handlerInstantiator = paramHandlerInstantiator; }
@Deprecated public JSONPObject(String paramString, Object paramObject, Class<?> paramClass) { this._function = paramString; this._value = paramObject; if (paramClass == null); for (JavaType localJavaType = null; ; localJavaType = TypeFactory.defaultInstance().constructType(paramClass)) { this._serializationType = localJavaType; return; } }
@Deprecated public JSONWrappedObject(String paramString1, String paramString2, Object paramObject, Class<?> paramClass) { this._prefix = paramString1; this._suffix = paramString2; this._value = paramObject; if (paramClass == null); for (JavaType localJavaType = null; ; localJavaType = TypeFactory.defaultInstance().constructType(paramClass)) { this._serializationType = localJavaType; return; } }
/** * Converts the data to a byte array * * @param source the object to convert to a byte array * @return the serialized version of the source object * @throws ConversionException if there was an issue reading/writing to the database. */ public byte[] toByteArray(final T source) throws ConversionException { TypeFactory typeFactory = mapper.getTypeFactory(); JavaType type = constructType(typeFactory); try { return mapper.writerWithType(type).writeValueAsBytes(source); } catch (IOException e) { throw new ConversionException(e); } }
/** * Converts the raw byte array data to an object * * @param raw the serialized object * @return the object which was read from the serialized byte array * @throws ConversionException if there was an issue reading/writing to the database. */ public T fromByteArray(byte[] raw) throws ConversionException { try { TypeFactory typeFactory = mapper.getTypeFactory(); JavaType type = constructType(typeFactory); return mapper.readValue(raw, type); } catch (IOException e) { throw new ConversionException(e); } }