com.fasterxml.jackson.databind.JavaType Java Examples
The following examples show how to use
com.fasterxml.jackson.databind.JavaType.
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: JacksonRequest.java From volley-jackson-extension with Apache License 2.0 | 7 votes |
@Override protected Response<T> parseNetworkResponse(NetworkResponse response) { JavaType returnType = mListener.getReturnType(); T returnData = null; if (returnType != null) { try { if (response.data != null) { returnData = OBJECT_MAPPER.readValue(response.data, returnType); } else if (response instanceof JacksonNetworkResponse) { returnData = OBJECT_MAPPER.readValue(((JacksonNetworkResponse)response).inputStream, returnType); } } catch (Exception e) { VolleyLog.e(e, "An error occurred while parsing network response:"); return Response.error(new ParseError(response)); } } return mListener.onParseResponseComplete(Response.success(returnData, HttpHeaderParser.parseCacheHeaders(response))); }
Example #2
Source File: TypeParser.java From lams with GNU General Public License v2.0 | 6 votes |
protected JavaType parseType(MyTokenizer tokens) throws IllegalArgumentException { if (!tokens.hasMoreTokens()) { throw _problem(tokens, "Unexpected end-of-string"); } Class<?> base = findClass(tokens.nextToken(), tokens); // either end (ok, non generic type), or generics if (tokens.hasMoreTokens()) { String token = tokens.nextToken(); if ("<".equals(token)) { List<JavaType> parameterTypes = parseTypes(tokens); TypeBindings b = TypeBindings.create(base, parameterTypes); return _factory._fromClass(null, base, b); } // can be comma that separates types, or closing '>' tokens.pushBack(token); } return _factory._fromClass(null, base, TypeBindings.emptyBindings()); }
Example #3
Source File: KvMapperFactory.java From haven-platform with Apache License 2.0 | 6 votes |
<T> Map<String, T> loadProps(Class<?> clazz, Function<KvProperty, T> func) { ImmutableMap.Builder<String, T> b = ImmutableMap.builder(); TypeFactory tf = TypeFactory.defaultInstance(); while(clazz != null && !Object.class.equals(clazz)) { for(Field field: clazz.getDeclaredFields()) { KvMapping mapping = field.getAnnotation(KvMapping.class); if(mapping == null) { continue; } JavaType javaType; String typeStr = mapping.type(); if(!typeStr.isEmpty()) { javaType = tf.constructFromCanonical(typeStr); } else { javaType = tf.constructType(field.getGenericType()); } KvProperty property = new KvProperty(this, field.getName(), field, javaType); b.put(property.getKey(), func.apply(property)); } clazz = clazz.getSuperclass(); } return b.build(); }
Example #4
Source File: RpcClient.java From consensusj with Apache License 2.0 | 6 votes |
private <R> JsonRpcResponse<R> responseFromStream(InputStream inputStream, JavaType responseType) throws IOException { JsonRpcResponse<R> responseJson; try { if (log.isDebugEnabled()) { // If logging enabled, copy InputStream to string and log String responseBody = convertStreamToString(inputStream); log.debug("Response Body: {}", responseBody); responseJson = mapper.readValue(responseBody, responseType); } else { // Otherwise convert directly to responseType responseJson = mapper.readValue(inputStream, responseType); } } catch (JsonProcessingException e) { log.error("JsonProcessingException: {}", e); // TODO: Map to some kind of JsonRPC exception similar to JsonRPCStatusException throw e; } return responseJson; }
Example #5
Source File: TypeFactory.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Method for constructing a {@link CollectionType}. *<p> * NOTE: type modifiers are NOT called on Collection type itself; but are called * for contained types. */ public CollectionType constructCollectionType(Class<? extends Collection> collectionClass, JavaType elementType) { TypeBindings bindings = TypeBindings.createIfNeeded(collectionClass, elementType); CollectionType result = (CollectionType) _fromClass(null, collectionClass, bindings); // 17-May-2017, tatu: As per [databind#1415], we better verify bound values if (but only if) // type being resolved was non-generic (i.e.element type was ignored) if (bindings.isEmpty() && (elementType != null)) { JavaType t = result.findSuperType(Collection.class); JavaType realET = t.getContentType(); if (!realET.equals(elementType)) { throw new IllegalArgumentException(String.format( "Non-generic Collection class %s did not resolve to something with element type %s but %s ", ClassUtil.nameOf(collectionClass), elementType, realET)); } } return result; }
Example #6
Source File: VersionTest.java From docker-java with Apache License 2.0 | 6 votes |
@Test public void testSerDer1() throws Exception { final JavaType type = JSONTestHelper.getMapper().getTypeFactory().constructType(Version.class); final Version version = testRoundTrip(RemoteApiVersion.VERSION_1_22, "/version/1.json", type ); assertThat(version, notNullValue()); assertThat(version.getVersion(), is("1.10.1")); assertThat(version.getApiVersion(), is("1.22")); assertThat(version.getGitCommit(), is("9e83765")); assertThat(version.getGoVersion(), is("go1.5.3")); assertThat(version.getOperatingSystem(), is("linux")); assertThat(version.getArch(), is("amd64")); assertThat(version.getKernelVersion(), is("4.1.17-boot2docker")); assertThat(version.getBuildTime(), is("2016-02-11T20:39:58.688092588+00:00")); }
Example #7
Source File: JsonConverter.java From BlogManagePlatform with Apache License 2.0 | 6 votes |
/** * Determine whether to log the given exception coming from a {@link ObjectMapper#canDeserialize} / * {@link ObjectMapper#canSerialize} check. * @param type the class that Jackson tested for (de-)serializability * @param cause the Jackson-thrown exception to evaluate (typically a {@link JsonMappingException}) * @since 4.3 */ private void logWarningIfNecessary(Type type, @Nullable Throwable cause) { if (cause == null) { return; } // Do not log warning for serializer not found (note: different message wording on Jackson 2.9) boolean debugLevel = cause instanceof JsonMappingException && cause.getMessage().startsWith("Cannot find"); if (debugLevel ? logger.isDebugEnabled() : logger.isWarnEnabled()) { String msg = StrUtil.concat("Failed to evaluate Jackson ", type instanceof JavaType ? "de" : "", "serialization for type [", type .toString(), "]"); if (debugLevel) { logger.debug(msg, cause); } else if (logger.isDebugEnabled()) { logger.warn(msg, cause); } else { logger.warn(msg + ": " + cause); } } }
Example #8
Source File: ToolManager.java From hugegraph-tools with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") protected <T> List<T> readList(String key, Class<T> clazz, String content) { ObjectMapper mapper = this.client.mapper(); try { JsonNode root = mapper.readTree(content); JsonNode element = root.get(key); if(element == null) { throw new SerializeException( "Can't find value of the key: %s in json.", key); } else { JavaType t = mapper.getTypeFactory() .constructParametricType(List.class, clazz); return (List<T>) mapper.readValue(element.toString(), t); } } catch (IOException e) { throw new SerializeException( "Failed to deserialize %s", e, content); } }
Example #9
Source File: BasicClassIntrospector.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Method called to see if type is one of core JDK types * that we have cached for efficiency. */ protected BasicBeanDescription _findStdTypeDesc(JavaType type) { Class<?> cls = type.getRawClass(); if (cls.isPrimitive()) { if (cls == Boolean.TYPE) { return BOOLEAN_DESC; } if (cls == Integer.TYPE) { return INT_DESC; } if (cls == Long.TYPE) { return LONG_DESC; } } else { if (cls == String.class) { return STRING_DESC; } } return null; }
Example #10
Source File: ModelResolverExt.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@Override public Model resolve(JavaType type, ModelConverterContext context, Iterator<ModelConverter> next) { // property is not a model if (propertyCreatorMap.containsKey(type.getRawClass())) { return null; } Model model = super.resolve(type, context, next); if (model == null) { return null; } checkType(type); // 只有声明model的地方才需要标注类型 if (model instanceof ModelImpl && !StringUtils.isEmpty(((ModelImpl) model).getName())) { setType(type, model.getVendorExtensions()); } return model; }
Example #11
Source File: TestJsonInstanceSerializerCompatibility.java From curator with Apache License 2.0 | 6 votes |
@Test public void testBackwardCompatibility() throws Exception { JsonInstanceSerializer<TestJsonInstanceSerializer.Payload> serializer = new JsonInstanceSerializer<TestJsonInstanceSerializer.Payload>(TestJsonInstanceSerializer.Payload.class, true, true); ServiceInstance<TestJsonInstanceSerializer.Payload> instance = new ServiceInstance<TestJsonInstanceSerializer.Payload>("name", "id", "address", 10, 20, new TestJsonInstanceSerializer.Payload("test"), 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), false); byte[] bytes = serializer.serialize(instance); instance = serializer.deserialize(bytes); Assert.assertTrue(instance.isEnabled()); // passed false for enabled in the ctor but that is lost with compatibleSerializationMode ObjectMapper mapper = new ObjectMapper(); JavaType type = mapper.getTypeFactory().constructType(OldServiceInstance.class); OldServiceInstance rawServiceInstance = mapper.readValue(bytes, type); TestJsonInstanceSerializer.Payload.class.cast(rawServiceInstance.getPayload()); // just to verify that it's the correct type //noinspection unchecked OldServiceInstance<TestJsonInstanceSerializer.Payload> check = (OldServiceInstance<TestJsonInstanceSerializer.Payload>)rawServiceInstance; Assert.assertEquals(check.getName(), instance.getName()); Assert.assertEquals(check.getId(), instance.getId()); Assert.assertEquals(check.getAddress(), instance.getAddress()); Assert.assertEquals(check.getPort(), instance.getPort()); Assert.assertEquals(check.getSslPort(), instance.getSslPort()); Assert.assertEquals(check.getPayload(), instance.getPayload()); Assert.assertEquals(check.getRegistrationTimeUTC(), instance.getRegistrationTimeUTC()); Assert.assertEquals(check.getServiceType(), instance.getServiceType()); Assert.assertEquals(check.getUriSpec(), instance.getUriSpec()); }
Example #12
Source File: AuthConfigTest.java From docker-java with Apache License 2.0 | 6 votes |
@Test public void serderDocs1() throws IOException { final JavaType type = JSONTestHelper.getMapper().getTypeFactory().constructType(AuthConfig.class); final AuthConfig authConfig = testRoundTrip(RemoteApiVersion.VERSION_1_22, "/other/AuthConfig/docs1.json", type ); assertThat(authConfig, notNullValue()); assertThat(authConfig.getUsername(), is("jdoe")); assertThat(authConfig.getPassword(), is("secret")); assertThat(authConfig.getEmail(), is("[email protected]")); final AuthConfig authConfig1 = new AuthConfig().withUsername("jdoe") .withPassword("secret") .withEmail("[email protected]"); assertThat(authConfig1, equalTo(authConfig)); }
Example #13
Source File: PipelineOptionsFactory.java From beam with Apache License 2.0 | 6 votes |
/** * Returns true if the given type is an array or {@link Collection} of {@code SIMPLE_TYPES} or * enums, or if the given type is a {@link ValueProvider ValueProvider<T>} and {@code T} is * an array or {@link Collection} of {@code SIMPLE_TYPES} or enums. */ private static boolean isCollectionOrArrayOfAllowedTypes(Class<?> type, JavaType genericType) { JavaType containerType = type.equals(ValueProvider.class) ? genericType.containedType(0) : genericType; // Check if it is an array of simple types or enum. if (containerType.getRawClass().isArray() && (SIMPLE_TYPES.contains(containerType.getRawClass().getComponentType()) || containerType.getRawClass().getComponentType().isEnum())) { return true; } // Check if it is Collection of simple types or enum. if (Collection.class.isAssignableFrom(containerType.getRawClass())) { JavaType innerType = containerType.containedType(0); // Note that raw types are allowed, hence the null check. if (innerType == null || SIMPLE_TYPES.contains(innerType.getRawClass()) || innerType.getRawClass().isEnum()) { return true; } } return false; }
Example #14
Source File: POJOProperty.java From jackson-modules-base with Apache License 2.0 | 5 votes |
private JavaType moreSpecificType(JavaType desc1, JavaType desc2) { Class<?> c1 = desc1.getRawClass(); Class<?> c2 = desc2.getRawClass(); if (c1.isAssignableFrom(c2)) { // c2 more specific than c1 return desc2; } if (c2.isAssignableFrom(c1)) { // c1 more specific than c2 return desc1; } // not compatible, so: return null; }
Example #15
Source File: RefKeyHandler.java From jackson-datatypes-collections with Apache License 2.0 | 5 votes |
public RefKeyHandler(JavaType keyType, KeyDeserializer _keyDeserializer) { if (keyType == null) { throw new IllegalArgumentException("keyType == null"); } this._keyType = keyType; this._keyDeserializer = _keyDeserializer; }
Example #16
Source File: DataHandlerJsonSerializer.java From jackson-modules-base with Apache License 2.0 | 5 votes |
@Override public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException { if (visitor != null) { JsonArrayFormatVisitor v2 = visitor.expectArrayFormat(typeHint); if (v2 != null) { v2.itemsFormat(JsonFormatTypes.STRING); } } }
Example #17
Source File: ParameterJavaTypeDiscoverer.java From evernote-rest-webapp with Apache License 2.0 | 5 votes |
/** * Resolve jackson {@link JavaType}s for the given method's parameters. * * @param actualMethod a method to resolve parameters * @return array of JavaTypes */ public JavaType[] getParameterJavaTypes(Method actualMethod) { JavaType[] javaTypes = this.javaTypesCache.get(actualMethod); if (javaTypes == null) { javaTypes = resolveParameterJavaTypes(actualMethod); this.javaTypesCache.put(actualMethod, javaTypes); } return javaTypes; }
Example #18
Source File: HighwayJsonUtils.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") public static <T> T convertValue(Object fromValue, JavaType toValueType) { if (fromValue == null) { return null; } if (TypeFactory.defaultInstance().constructType(LocalDateTime.class).equals(toValueType)) { // jackson do not have a proper converter for this. if (fromValue instanceof Date) { return (T) LocalDateTime.ofInstant(Instant.ofEpochMilli(((Date) fromValue).getTime()), ZoneOffset.UTC); } } return OBJ_MAPPER.convertValue(fromValue, toValueType); }
Example #19
Source File: Config.java From digdag with Apache License 2.0 | 5 votes |
private Object readObject(JavaType type, JsonNode value, String key) { try { return mapper.readValue(value.traverse(), type); } catch (Exception ex) { throw propagateConvertException(ex, typeNameOf(type), value, key); } }
Example #20
Source File: ExampleJacksonReladomoSerializerListTest.java From reladomo with Apache License 2.0 | 5 votes |
protected SerializedList toSerializedString(String json) throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JacksonReladomoModule()); mapper.enable(SerializationFeature.INDENT_OUTPUT); JavaType customClassCollection = mapper.getTypeFactory().constructMapLikeType(SerializedList.class, Order.class, OrderList.class); return mapper.readValue(json, customClassCollection); // return mapper.readValue(json, new TypeReference<Serialized<Order>>() {}); // return mapper.readValue(json, Serialized.class); }
Example #21
Source File: LightCache.java From Milkomeda with MIT License | 5 votes |
@Override public <E> Spot<Serializable, E> get(String key, TypeReference<Serializable> vTypeRef, TypeReference<E> eTypeRef) { // TypeReference -> (Type | JavaType) -> Class // TypeFactory.defaultInstance().constructType(SerializableTypeRef.getType()).getRawClass(); JavaType vType = TypeFactory.defaultInstance().constructType(vTypeRef); JavaType eType = TypeFactory.defaultInstance().constructType(eTypeRef); JavaType javaType = TypeFactory.defaultInstance() .constructParametricType(discardStrategy.spotClazz(), vType, eType); return get(key, javaType); }
Example #22
Source File: RpcClient.java From consensusj with Apache License 2.0 | 5 votes |
/** * Prepare and throw JsonRPCStatusException with all relevant info * @param responseCode Non-success response code * @param connection the current connection * @throws IOException IO Error * @throws JsonRpcStatusException An exception containing the HTTP status code and a message */ private void handleBadResponseCode(int responseCode, HttpURLConnection connection) throws IOException, JsonRpcStatusException { String responseMessage = connection.getResponseMessage(); String exceptionMessage = responseMessage; int jsonRpcCode = 0; JsonRpcResponse bodyJson = null; // Body as JSON if available String bodyString = null; // Body as String if not JSON InputStream errorStream = connection.getErrorStream(); if (errorStream != null) { if (connection.getContentType().equals("application/json")) { JavaType genericResponseType = mapper.getTypeFactory(). constructParametricType(JsonRpcResponse.class, JsonNode.class); // We got a JSON error response -- try to parse it as a JsonRpcResponse bodyJson = responseFromStream(errorStream, genericResponseType); JsonRpcError error = bodyJson.getError(); if (error != null) { // If there's a more specific message in the JSON use it instead. exceptionMessage = error.getMessage(); jsonRpcCode = error.getCode(); // Since this is an error at the JSON level, let's log it with `info` level and // let the higher-level software decide whether to log it as `error` or not. // i.e. The higher-level software can set error level on this module to `warn` and then // decide whether to log this "error" not based upon the JsonRpcStatusException thrown. // An example occurs in Bitcoin when a client is waiting for a server to initialize // and returns 'Still scanning.. at block 530006 of 548850' log.info("json error code: {}, message: {}", jsonRpcCode, exceptionMessage); } } else { // No JSON, read response body as string bodyString = convertStreamToString(errorStream); log.error("error string: {}", bodyString); errorStream.close(); } } throw new JsonRpcStatusException(exceptionMessage, responseCode, responseMessage, jsonRpcCode, bodyString, bodyJson); }
Example #23
Source File: BodyParamExtractionTest.java From swagger-inflector with Apache License 2.0 | 5 votes |
@Test public void testConvertPrimitiveArrayBodyParam() throws Exception { Map<String, Schema> definitions = ModelConverters.getInstance().read(Person.class); RequestBody body = new RequestBody(). content(new Content() .addMediaType("application/json",new MediaType().schema(new ArraySchema() .items(new StringSchema())))); JavaType jt = utils.getTypeFromRequestBody(body, "application/json" ,definitions)[0]; assertNotNull(jt); assertEquals(jt.getRawClass(), String[].class); }
Example #24
Source File: AbstractJackson2HttpMessageConverter.java From lams with GNU General Public License v2.0 | 5 votes |
@Override protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { JavaType javaType = getJavaType(clazz, null); return readJavaType(javaType, inputMessage); }
Example #25
Source File: ConstantSerializer.java From Rosetta with Apache License 2.0 | 5 votes |
@Override public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) { // try/catch is for 2.1.x compatibility try { DELEGATE.acceptJsonFormatVisitor(visitor, typeHint); } catch (Exception e) { throw new RuntimeException(e); } }
Example #26
Source File: ResolvedRecursiveType.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public JavaType getSuperClass() { if (_referencedType != null) { return _referencedType.getSuperClass(); } return super.getSuperClass(); }
Example #27
Source File: TypeFactory.java From lams with GNU General Public License v2.0 | 5 votes |
protected JavaType _resolveSuperClass(ClassStack context, Class<?> rawType, TypeBindings parentBindings) { Type parent = ClassUtil.getGenericSuperclass(rawType); if (parent == null) { return null; } return _fromAny(context, parent, parentBindings); }
Example #28
Source File: BasicClassIntrospector.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public BasicBeanDescription forDirectClassAnnotations(MapperConfig<?> config, JavaType type, MixInResolver r) { BasicBeanDescription desc = _findStdTypeDesc(type); if (desc == null) { desc = BasicBeanDescription.forOtherUse(config, type, _resolveAnnotatedWithoutSuperTypes(config, type, r)); } return desc; }
Example #29
Source File: StringPropertyConverter.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
@Override public JavaType doConvert(Swagger swagger, Object property) { StringProperty stringProperty = (StringProperty) property; List<String> enums = stringProperty.getEnum(); if (!isEnum(enums)) { return ConverterMgr.findJavaType(stringProperty.getType(), stringProperty.getFormat()); } return OBJECT_JAVA_TYPE; }
Example #30
Source File: EnumSchemaUtils.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
public static <T> T constructEnumArrayClass(JavaType javaType) { if (javaType.isArrayType()) { return ReflectUtils.constructArrayType(javaType.getContentType().getRawClass()); } return ReflectUtils.constructArrayType(Object.class); }