List of usage examples for com.fasterxml.jackson.core JsonParser getCurrentToken
public abstract JsonToken getCurrentToken();
From source file:com.addthis.codec.jackson.CodecTypeDeserializer.java
@Override public Object deserializeTypedFromAny(JsonParser jp, DeserializationContext ctxt) throws IOException { // a jackson thing we might as well include if (jp.canReadTypeId()) { Object typeId = jp.getTypeId(); if (typeId != null) { return _deserializeWithNativeTypeId(jp, ctxt, typeId); }//from w w w . ja v a 2 s . co m } // can use this to approximate error location if a sub-method throws an exception JsonLocation currentLocation = jp.getTokenLocation(); JsonNode jsonNode; // empty objects can appear with END_OBJECT. that has special handling lots of places, but not in readTree if (jp.getCurrentToken() == JsonToken.END_OBJECT) { jsonNode = ctxt.getNodeFactory().objectNode(); } else { jsonNode = jp.readValueAsTree(); } ObjectCodec objectCodec = jp.getCodec(); try { Object bean = null; // _array handler if (jsonNode.isArray()) { bean = _deserializeTypedFromArray((ArrayNode) jsonNode, objectCodec, ctxt); // object handler } else if (jsonNode.isObject()) { bean = _deserializeTypedFromObject((ObjectNode) jsonNode, objectCodec, ctxt); } if (bean != null) { return bean; } else { // Jackson 2.6+ throws NPE on null typeId parameter (underlying Map changed from HashMap // to ConcurrentHashMap), so use empty string instead of null JsonDeserializer<Object> deser = _findDeserializer(ctxt, ""); JsonParser treeParser = jp.getCodec().treeAsTokens(jsonNode); treeParser.nextToken(); return deser.deserialize(treeParser, ctxt); } } catch (JsonMappingException ex) { throw Jackson.maybeImproveLocation(currentLocation, ex); } }
From source file:com.github.shyiko.jackson.module.advice.AdvisedBeanDeserializer.java
protected Object deserializeWithExternalTypeId(JsonParser jp, DeserializationContext ctxt, Object bean) throws IOException { final Class<?> activeView = _needViewProcesing ? ctxt.getActiveView() : null; final ExternalTypeHandler ext = _externalTypeIdHandler.start(); beanDeserializerAdvice.before(bean, jp, ctxt); for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) { String propName = jp.getCurrentName(); jp.nextToken();/*from ww w .j a va 2 s . com*/ if (beanDeserializerAdvice.intercept(bean, propName, jp, ctxt)) { continue; } SettableBeanProperty prop = _beanProperties.find(propName); if (prop != null) { // normal case // [JACKSON-831]: may have property AND be used as external type id: if (jp.getCurrentToken().isScalarValue()) { ext.handleTypePropertyValue(jp, ctxt, propName, bean); } if (activeView != null && !prop.visibleInView(activeView)) { jp.skipChildren(); continue; } try { prop.deserializeAndSet(jp, ctxt, bean); } catch (Exception e) { wrapAndThrow(e, bean, propName, ctxt); } continue; } // ignorable things should be ignored if (_ignorableProps != null && _ignorableProps.contains(propName)) { handleIgnoredProperty(jp, ctxt, bean, propName); continue; } // but others are likely to be part of external type id thingy... if (ext.handlePropertyValue(jp, ctxt, propName, bean)) { continue; } // if not, the usual fallback handling: if (_anySetter != null) { try { _anySetter.deserializeAndSet(jp, ctxt, bean, propName); } catch (Exception e) { wrapAndThrow(e, bean, propName, ctxt); } continue; } // Unknown: let's call handler method handleUnknownProperty(jp, ctxt, bean, propName); } // and when we get this far, let's try finalizing the deal: ext.complete(jp, ctxt, bean); beanDeserializerAdvice.after(bean, jp, ctxt); return bean; }
From source file:org.h2gis.drivers.geojson.GeoJsonReaderDriver.java
/** * Parses a sequence of coordinates array expressed as * * [ [100.0, 0.0], [101.0, 1.0] ]/* w w w . j a v a2 s . c o m*/ * * @param jp * @throws IOException * @throws SQLException * @return Coordinate[] */ private Coordinate[] parseCoordinates(JsonParser jp) throws IOException { jp.nextToken(); // START_ARRAY [ to parse the each positions ArrayList<Coordinate> coords = new ArrayList<Coordinate>(); while (jp.getCurrentToken() != JsonToken.END_ARRAY) { coords.add(parseCoordinate(jp)); } return coords.toArray(new Coordinate[coords.size()]); }
From source file:com.adobe.communities.ugc.migration.importer.UGCImportHelper.java
protected void extractEvent(final JsonParser jsonParser, final Resource resource) throws IOException { String author = null;//from w w w. ja va 2 s. c o m final JSONObject requestParams = new JSONObject(); try { jsonParser.nextToken(); JsonToken token = jsonParser.getCurrentToken(); while (token.equals(JsonToken.FIELD_NAME)) { String field = jsonParser.getCurrentName(); jsonParser.nextToken(); if (field.equals(PN_START) || field.equals(PN_END)) { final Long value = jsonParser.getValueAsLong(); final Calendar calendar = new GregorianCalendar(); calendar.setTimeInMillis(value); final Date date = calendar.getTime(); final TimeZone tz = TimeZone.getTimeZone("UTC"); // this is the ISO-8601 format expected by the CalendarOperations object final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm+00:00"); df.setTimeZone(tz); if (field.equals(PN_START)) { requestParams.put(CalendarRequestConstants.START_DATE, df.format(date)); } else { requestParams.put(CalendarRequestConstants.END_DATE, df.format(date)); } } else if (field.equals(CalendarRequestConstants.TAGS)) { List<String> tags = new ArrayList<String>(); if (jsonParser.getCurrentToken().equals(JsonToken.START_ARRAY)) { token = jsonParser.nextToken(); while (!token.equals(JsonToken.END_ARRAY)) { tags.add(URLDecoder.decode(jsonParser.getValueAsString(), "UTF-8")); token = jsonParser.nextToken(); } requestParams.put(CalendarRequestConstants.TAGS, tags); } else { LOG.warn("Tags field came in without an array of tags in it - not processed"); // do nothing, just log the error } } else if (field.equals("jcr:createdBy")) { author = URLDecoder.decode(jsonParser.getValueAsString(), "UTF-8"); } else if (field.equals(ContentTypeDefinitions.LABEL_TIMESTAMP_FIELDS)) { jsonParser.skipChildren(); // we do nothing with these because they're going to be put into json } else { try { final String value = URLDecoder.decode(jsonParser.getValueAsString(), "UTF-8"); requestParams.put(field, value); } catch (NullPointerException e) { throw e; } } token = jsonParser.nextToken(); } } catch (final JSONException e) { throw new IOException("Unable to build a JSON object with the inputs provided", e); } try { Map<String, Object> eventParams = new HashMap<String, Object>(); eventParams.put("event", requestParams.toString()); calendarOperations.create(resource, author, eventParams, null, resource.getResourceResolver().adaptTo(Session.class)); } catch (final OperationException e) { //probably caused by creating a folder that already exists. We ignore it, but still log the event. LOG.info("There was an operation exception while creating an event"); } }
From source file:com.zenesis.qx.remote.RequestHandler.java
/** * Reads the current token value, with special consideration for enums * @param jp/*from ww w.j ava2 s. c om*/ * @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.github.shyiko.jackson.module.advice.AdvisedBeanDeserializer.java
@SuppressWarnings("resource") protected Object deserializeUsingPropertyBasedWithUnwrapped(JsonParser jp, DeserializationContext ctxt) throws IOException { final PropertyBasedCreator creator = _propertyBasedCreator; PropertyValueBuffer buffer = creator.startBuilding(jp, ctxt, _objectIdReader); TokenBuffer tokens = new TokenBuffer(jp); tokens.writeStartObject();/*w w w.j a v a 2s.c o m*/ JsonToken t = jp.getCurrentToken(); for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) { String propName = jp.getCurrentName(); jp.nextToken(); // to point to value // creator property? SettableBeanProperty creatorProp = creator.findCreatorProperty(propName); if (creatorProp != null) { // Last creator property to set? Object value = creatorProp.deserialize(jp, ctxt); if (buffer.assignParameter(creatorProp.getCreatorIndex(), value)) { t = jp.nextToken(); // to move to following FIELD_NAME/END_OBJECT Object bean; try { bean = creator.build(ctxt, buffer); } catch (Exception e) { wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt); continue; // never gets here } // if so, need to copy all remaining tokens into buffer while (t == JsonToken.FIELD_NAME) { jp.nextToken(); // to skip name tokens.copyCurrentStructure(jp); t = jp.nextToken(); } tokens.writeEndObject(); if (bean.getClass() != _beanType.getRawClass()) { // !!! 08-Jul-2011, tatu: Could probably support; but for now // it's too complicated, so bail out tokens.close(); throw ctxt.mappingException("Can not create polymorphic instances with unwrapped values"); } return _unwrappedPropertyHandler.processUnwrapped(jp, ctxt, bean, tokens); } continue; } // Object Id property? if (buffer.readIdProperty(propName)) { continue; } // regular property? needs buffering SettableBeanProperty prop = _beanProperties.find(propName); if (prop != null) { buffer.bufferProperty(prop, prop.deserialize(jp, ctxt)); continue; } /* As per [JACKSON-313], things marked as ignorable should not be * passed to any setter */ if (_ignorableProps != null && _ignorableProps.contains(propName)) { handleIgnoredProperty(jp, ctxt, handledType(), propName); continue; } tokens.writeFieldName(propName); tokens.copyCurrentStructure(jp); // "any property"? if (_anySetter != null) { buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(jp, ctxt)); } } // We hit END_OBJECT, so: Object bean; try { bean = creator.build(ctxt, buffer); } catch (Exception e) { wrapInstantiationProblem(e, ctxt); return null; // never gets here } return _unwrappedPropertyHandler.processUnwrapped(jp, ctxt, bean, tokens); }
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// ww w .ja v 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())); }
From source file:org.emfjson.jackson.databind.deser.ResourceDeserializer.java
@Override public Resource deserialize(JsonParser jp, DeserializationContext ctxt, Resource intoValue) throws IOException { final Resource resource = getResource(ctxt, intoValue); if (resource == null) { throw new IllegalArgumentException("Invalid resource"); }//from w w w . j ava 2 s . c om final ReferenceEntries entries = new ReferenceEntries(); final EcoreTypeFactory ecoreType = new EcoreTypeFactory(); final ResourceSet resourceSet = resource.getResourceSet(); ctxt.setAttribute(RESOURCE, resource); ctxt.setAttribute(REFERENCE_ENTRIES, entries); ctxt.setAttribute(CACHE, new Cache()); ctxt.setAttribute(TYPE_FACTORY, ecoreType); ctxt.setAttribute(RESOURCE_SET, resourceSet); if (!jp.hasCurrentToken()) { jp.nextToken(); } final TypeFactory factory = TypeFactory.defaultInstance(); final JsonDeserializer<Object> deserializer = ctxt .findRootValueDeserializer(factory.constructType(EObject.class)); if (jp.getCurrentToken() == JsonToken.START_ARRAY) { while (jp.nextToken() != JsonToken.END_ARRAY) { EObject value = (EObject) deserializer.deserialize(jp, ctxt); if (value != null) { resource.getContents().add(value); } } } else if (jp.getCurrentToken() == JsonToken.START_OBJECT) { EObject value = (EObject) deserializer.deserialize(jp, ctxt); if (value != null) { resource.getContents().add(value); } } entries.resolve(resourceSet, uriHandler); return resource; }
From source file:com.zenesis.qx.remote.RequestHandler.java
/** * Reads an array from JSON, where each value is of the listed in types; EG the first element * is class type[0], the second element is class type[1] etc * @param jp/*from w ww . j a va2 s.c o m*/ * @param types * @return * @throws IOException */ private Object[] readArray(JsonParser jp, Class[] types) throws IOException { if (jp.getCurrentToken() == JsonToken.VALUE_NULL) return null; ArrayList result = new ArrayList(); for (int paramIndex = 0; jp.nextToken() != JsonToken.END_ARRAY; paramIndex++) { Class type = null; if (types != null && paramIndex < types.length) type = types[paramIndex]; if (type != null && type.isArray()) { if (jp.getCurrentToken() == JsonToken.VALUE_NULL) result.add(null); else if (jp.getCurrentToken() == JsonToken.START_ARRAY) { Object obj = readArray(jp, type.getComponentType()); result.add(obj); } else throw new IllegalStateException("Expected array but found " + jp.getCurrentToken()); } else if (type != null && Proxied.class.isAssignableFrom(type)) { Integer id = jp.readValueAs(Integer.class); if (id != null) { Proxied obj = getProxied(id); result.add(obj); } else result.add(null); } else if (type != null && Enum.class.isAssignableFrom(type)) { Object obj = jp.readValueAs(Object.class); if (obj != null) { String str = Helpers.camelCaseToEnum(obj.toString()); obj = Enum.valueOf(type, str); result.add(obj); } } else { Object obj = jp.readValueAs(type != null ? type : Object.class); result.add(obj); } } return result.toArray(new Object[result.size()]); }
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/*from w ww .j av a2 s . c o m*/ * @param clazz * @return * @throws IOException */ private Map readMap(JsonParser jp, Class keyClazz, Class clazz) throws IOException { if (jp.getCurrentToken() == JsonToken.VALUE_NULL) return null; boolean isProxyClass = Proxied.class.isAssignableFrom(clazz); if (keyClazz == null) keyClazz = String.class; HashMap result = new HashMap(); for (; jp.nextToken() != JsonToken.END_OBJECT;) { Object key = readSimpleValue(jp, keyClazz); jp.nextToken(); if (isProxyClass) { Integer id = jp.readValueAs(Integer.class); if (id != null) { Proxied obj = getProxied(id); if (!clazz.isInstance(obj)) throw new ClassCastException( "Cannot cast " + obj + " class " + obj.getClass() + " to " + clazz); result.put(key, obj); } else result.put(key, null); } else { Object obj = readSimpleValue(jp, clazz); result.put(key, obj); } } return result; }