List of usage examples for com.fasterxml.jackson.core JsonParser readValueAs
@SuppressWarnings("unchecked") public <T> T readValueAs(TypeReference<?> valueTypeRef) throws IOException, JsonProcessingException
From source file:org.labkey.freezerpro.export.FreezerProCommandResonse.java
/** * Position the parser to the start of the data array object * @param parser/*ww w . j a va 2 s. c o m*/ * @param dataNodeName * @return * @throws IOException */ protected boolean ensureDataNode(JsonParser parser, String dataNodeName) throws IOException { JsonToken token = parser.nextToken(); //JsonUtil.expectObjectStart(parser); while (token != JsonToken.END_OBJECT) { token = parser.nextToken(); if (token == JsonToken.FIELD_NAME) { String fieldName = parser.getCurrentName(); if (dataNodeName.equals(fieldName)) { parser.nextToken(); return true; } else if (TOTAL_FIELD_NAME.equalsIgnoreCase(fieldName)) { JsonToken totalToken = parser.nextToken(); if (totalToken == JsonToken.VALUE_NUMBER_INT) { _totalRecords = parser.readValueAs(Integer.class); } } } } return false; }
From source file:org.apache.ode.jacob.soup.jackson.MessageDeserializer.java
@Override public Message deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { long id = 0;// w w w . j a va 2s . c o m String action = null; ChannelRef to = null; ChannelRef replyTo = null; Map<String, Object> headers = null; Object body = null; while (jp.nextToken() != JsonToken.END_OBJECT) { String fieldname = jp.getCurrentName(); if (jp.getCurrentToken() == JsonToken.FIELD_NAME) { // if we're not already on the field, advance by one. jp.nextToken(); } if ("id".equals(fieldname)) { id = jp.getLongValue(); } else if ("action".equals(fieldname)) { action = jp.getText(); } else if ("to".equals(fieldname)) { to = jp.readValueAs(ChannelRef.class); } else if ("replyTo".equals(fieldname)) { replyTo = jp.readValueAs(ChannelRef.class); } else if ("headers".equals(fieldname)) { headers = jp.readValueAs(mapTypeRef); } else if ("body".equals(fieldname)) { body = jp.readValueAs(Object.class); } } if (action == null) { throw ctxt.mappingException(Message.class); } if (to == null) { throw ctxt.mappingException(Message.class); } Message msg = new Message(to, replyTo, action); msg.setHeaders(headers); msg.setBody(body); msg.setId(id); return msg; }
From source file:io.coala.json.DynaBean.java
/** * @param referenceType/*w w w . j a va2 s . c o m*/ * @param <S> * @param <T> * @return */ static final <S, T> JsonDeserializer<T> createJsonDeserializer(final ObjectMapper om, final Class<T> resultType, final Properties... imports) { return new JsonDeserializer<T>() { @Override public T deserializeWithType(final JsonParser jp, final DeserializationContext ctxt, final TypeDeserializer typeDeserializer) throws IOException, JsonProcessingException { return deserialize(jp, ctxt); } @Override public T deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException { if (jp.getCurrentToken() == JsonToken.VALUE_NULL) return null; // if( Wrapper.class.isAssignableFrom( resultType ) ) // { // // FIXME // LOG.trace( "deser wrapper intf of {}", jp.getText() ); // return (T) Wrapper.Util.valueOf( jp.getText(), // resultType.asSubclass( Wrapper.class ) ); // } if (Config.class.isAssignableFrom(resultType)) { final Map<String, Object> entries = jp.readValueAs(new TypeReference<Map<String, Object>>() { }); final Iterator<Entry<String, Object>> it = entries.entrySet().iterator(); for (Entry<String, Object> next = null; it.hasNext(); next = it.next()) if (next != null && next.getValue() == null) { LOG.trace("Ignoring null value: {}", next); it.remove(); } return resultType.cast(ConfigFactory.create(resultType.asSubclass(Config.class), entries)); } // else if (Config.class.isAssignableFrom(resultType)) // throw new JsonGenerationException( // "Config does not extend "+Mutable.class.getName()+" required for deserialization: " // + Arrays.asList(resultType // .getInterfaces())); // can't parse directly to interface type final DynaBean bean = new DynaBean(); final TreeNode tree = jp.readValueAsTree(); // override attributes as defined in interface getters final Set<String> attributes = new HashSet<>(); for (Method method : resultType.getMethods()) { if (method.getReturnType().equals(Void.TYPE) || method.getParameterTypes().length != 0) continue; final String attribute = method.getName(); if (attribute.equals("toString") || attribute.equals("hashCode")) continue; attributes.add(attribute); final TreeNode value = tree.get(attribute);// bean.any().get(attributeName); if (value == null) continue; bean.set(method.getName(), om.treeToValue(value, JsonUtil.checkRegistered(om, method.getReturnType(), imports))); } if (tree.isObject()) { // keep superfluous properties as TreeNodes, just in case final Iterator<String> fieldNames = tree.fieldNames(); while (fieldNames.hasNext()) { final String fieldName = fieldNames.next(); if (!attributes.contains(fieldName)) bean.set(fieldName, tree.get(fieldName)); } } else if (tree.isValueNode()) { for (Class<?> type : resultType.getInterfaces()) for (Method method : type.getDeclaredMethods()) { // LOG.trace( "Scanning {}", method ); if (method.isAnnotationPresent(JsonProperty.class)) { final String property = method.getAnnotation(JsonProperty.class).value(); // LOG.trace( "Setting {}: {}", property, // ((ValueNode) tree).textValue() ); bean.set(property, ((ValueNode) tree).textValue()); } } } else throw ExceptionFactory.createUnchecked("Expected {} but parsed: {}", resultType, tree.getClass()); return DynaBean.proxyOf(om, resultType, bean, imports); } }; }
From source file:org.springframework.security.oauth2.common.exceptions.OAuth2ExceptionJackson2Deserializer.java
@Override public OAuth2Exception deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonToken t = jp.getCurrentToken();/*w ww . j a va2 s . co m*/ if (t == JsonToken.START_OBJECT) { t = jp.nextToken(); } Map<String, Object> errorParams = new HashMap<String, Object>(); for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) { // Must point to field name String fieldName = jp.getCurrentName(); // And then the value... t = jp.nextToken(); // Note: must handle null explicitly here; value deserializers won't Object value; if (t == JsonToken.VALUE_NULL) { value = null; } // Some servers might send back complex content else if (t == JsonToken.START_ARRAY) { value = jp.readValueAs(List.class); } else if (t == JsonToken.START_OBJECT) { value = jp.readValueAs(Map.class); } else { value = jp.getText(); } errorParams.put(fieldName, value); } Object errorCode = errorParams.get("error"); String errorMessage = errorParams.containsKey("error_description") ? errorParams.get("error_description").toString() : null; if (errorMessage == null) { errorMessage = errorCode == null ? "OAuth Error" : errorCode.toString(); } OAuth2Exception ex; if ("invalid_client".equals(errorCode)) { ex = new InvalidClientException(errorMessage); } else if ("unauthorized_client".equals(errorCode)) { ex = new UnauthorizedUserException(errorMessage); } else if ("invalid_grant".equals(errorCode)) { if (errorMessage.toLowerCase().contains("redirect") && errorMessage.toLowerCase().contains("match")) { ex = new RedirectMismatchException(errorMessage); } else { ex = new InvalidGrantException(errorMessage); } } else if ("invalid_scope".equals(errorCode)) { ex = new InvalidScopeException(errorMessage); } else if ("invalid_token".equals(errorCode)) { ex = new InvalidTokenException(errorMessage); } else if ("invalid_request".equals(errorCode)) { ex = new InvalidRequestException(errorMessage); } else if ("redirect_uri_mismatch".equals(errorCode)) { ex = new RedirectMismatchException(errorMessage); } else if ("unsupported_grant_type".equals(errorCode)) { ex = new UnsupportedGrantTypeException(errorMessage); } else if ("unsupported_response_type".equals(errorCode)) { ex = new UnsupportedResponseTypeException(errorMessage); } else if ("insufficient_scope".equals(errorCode)) { ex = new InsufficientScopeException(errorMessage, OAuth2Utils.parseParameterList((String) errorParams.get("scope"))); } else if ("access_denied".equals(errorCode)) { ex = new UserDeniedAuthorizationException(errorMessage); } else { ex = new OAuth2Exception(errorMessage); } Set<Map.Entry<String, Object>> entries = errorParams.entrySet(); for (Map.Entry<String, Object> entry : entries) { String key = entry.getKey(); if (!"error".equals(key) && !"error_description".equals(key)) { Object value = entry.getValue(); ex.addAdditionalInformation(key, value == null ? null : value.toString()); } } return ex; }
From source file:com.zenesis.qx.remote.RequestHandler.java
/** * Gets a field value from the parser, checking that it is the type expected * @param <T> The desired type of object returned * @param jp the parser/* w w w. ja v a2s . c o m*/ * @param fieldName the name of the field to get * @param clazz the class of the type to get * @return * @throws ServletException * @throws IOException */ private <T> T getFieldValue(JsonParser jp, String fieldName, Class<T> clazz) throws ServletException, IOException { skipFieldName(jp, fieldName); T obj = (T) jp.readValueAs(clazz); return obj; }
From source file:com.zenesis.qx.remote.RequestHandler.java
/** * Called when the client has disposed of * @param jp/*w ww. j av a 2s. co m*/ * @throws ServletException * @throws IOException */ protected void cmdDispose(JsonParser jp) throws ServletException, IOException { skipFieldName(jp, "serverIds"); while (jp.nextToken() != JsonToken.END_ARRAY) { int serverId = jp.readValueAs(Integer.class); tracker.forget(serverId); } jp.nextToken(); }
From source file:com.kaaprotech.satu.jackson.SatuDeserializers.java
@Override public JsonDeserializer<?> findMapDeserializer(final MapType type, final DeserializationConfig config, BeanDescription beanDesc, final KeyDeserializer keyDeserializer, final TypeDeserializer elementTypeDeserializer, final JsonDeserializer<?> elementDeserializer) throws JsonMappingException { if (ImmutableMap.class.isAssignableFrom(type.getRawClass())) { return new StdDeserializer<Object>(type) { private static final long serialVersionUID = 1L; @Override//from w w w . j ava 2s. com public Object deserialize(JsonParser jp, DeserializationContext context) throws IOException { JsonToken t = jp.getCurrentToken(); if (t == JsonToken.START_OBJECT) { t = jp.nextToken(); } if (t != JsonToken.FIELD_NAME && t != JsonToken.END_OBJECT) { throw context.mappingException(type.getRawClass()); } MutableMap<Object, Object> m = Maps.mutable.of(); for (; jp.getCurrentToken() == JsonToken.FIELD_NAME; jp.nextToken()) { // Pointing to field name String fieldName = jp.getCurrentName(); Object key = (keyDeserializer == null) ? fieldName : keyDeserializer.deserializeKey(fieldName, context); t = jp.nextToken(); Object value; if (t == JsonToken.VALUE_NULL) { value = null; } else if (elementDeserializer == null) { value = jp.readValueAs(type.getContentType().getRawClass()); } else if (elementTypeDeserializer == null) { value = elementDeserializer.deserialize(jp, context); } else { value = elementDeserializer.deserializeWithType(jp, context, elementTypeDeserializer); } m.put(key, value); } return m.toImmutable(); } }; } return super.findMapDeserializer(type, config, beanDesc, keyDeserializer, elementTypeDeserializer, elementDeserializer); }
From source file:com.bazaarvoice.jsonpps.PrettyPrintJson.java
private void copyCurrentStructure(JsonParser parser, ObjectMapper mapper, int depth, JsonGenerator generator) throws IOException { // Avoid using the mapper to parse the entire input until we absolutely must. This allows pretty // printing huge top-level arrays (that wouldn't fit in memory) containing smaller objects (that // individually do fit in memory) where the objects are printed with sorted keys. JsonToken t = parser.getCurrentToken(); if (t == null) { generator.copyCurrentStructure(parser); // Will report the error of a null token. return;// w w w . j a v a2s . c o m } int id = t.id(); if (id == ID_FIELD_NAME) { if (depth > flatten) { generator.writeFieldName(parser.getCurrentName()); } t = parser.nextToken(); id = t.id(); } switch (id) { case ID_START_OBJECT: if (sortKeys && depth >= flatten) { // Load the entire object in memory so we can sort its keys and serialize it back out. mapper.writeValue(generator, parser.readValueAs(Map.class)); } else { // Don't load the whole object into memory. Copy it in a memory-efficient streaming fashion. if (depth >= flatten) { generator.writeStartObject(); } while (parser.nextToken() != JsonToken.END_OBJECT) { copyCurrentStructure(parser, mapper, depth + 1, generator); } if (depth >= flatten) { generator.writeEndObject(); } } break; case ID_START_ARRAY: // Don't load the whole array into memory. Copy it in a memory-efficient streaming fashion. if (depth >= flatten) { generator.writeStartArray(); } while (parser.nextToken() != JsonToken.END_ARRAY) { copyCurrentStructure(parser, mapper, depth + 1, generator); } if (depth >= flatten) { generator.writeEndArray(); } break; default: generator.copyCurrentEvent(parser); break; } }
From source file:com.zenesis.qx.remote.RequestHandler.java
/** * Reads the current token value, with special consideration for enums * @param jp//from w w w . j av a 2 s .c o m * @param clazz * @return * @throws IOException */ private Object readSimpleValue(JsonParser jp, Class clazz) throws IOException { if (jp.getCurrentToken() == JsonToken.VALUE_NULL) return null; Object obj = null; if (Enum.class.isAssignableFrom(clazz)) { if (jp.getCurrentToken() == JsonToken.FIELD_NAME) obj = jp.getCurrentName(); else obj = jp.readValueAs(Object.class); if (obj != null) { String str = Helpers.camelCaseToEnum(obj.toString()); obj = Enum.valueOf(clazz, str); } } else { if (jp.getCurrentToken() == JsonToken.FIELD_NAME) obj = jp.getCurrentName(); else obj = jp.readValueAs(clazz); } return obj; }
From source file:com.zenesis.qx.remote.RequestHandler.java
/** * Reads an array from JSON, where each value is of the class clazz. Note that while the result * is an array, you cannot assume that it is an array of Object, or use generics because generics * are always Objects - this is because arrays of primitive types are not arrays of Objects * @param jp//w w w .j av a 2 s. c o m * @param clazz * @return * @throws IOException */ private Object readArray(JsonParser jp, Class clazz) throws IOException { if (jp.getCurrentToken() == JsonToken.VALUE_NULL) return null; boolean isProxyClass = Proxied.class.isAssignableFrom(clazz); ArrayList result = new ArrayList(); for (; jp.nextToken() != JsonToken.END_ARRAY;) { if (isProxyClass) { Integer id = jp.readValueAs(Integer.class); if (id != null) { Proxied obj = getProxied(id); if (obj == null) log.fatal("Cannot read object of class " + clazz + " from id=" + id); else if (!clazz.isInstance(obj)) throw new ClassCastException( "Cannot cast " + obj + " class " + obj.getClass() + " to " + clazz); else result.add(obj); } else result.add(null); } else { Object obj = readSimpleValue(jp, clazz); result.add(obj); } } Object arr = Array.newInstance(clazz, result.size()); for (int i = 0; i < result.size(); i++) Array.set(arr, i, result.get(i)); return arr; //return result.toArray(Array.newInstance(clazz, result.size())); }