List of usage examples for com.fasterxml.jackson.core JsonParser getCurrentLocation
public abstract JsonLocation getCurrentLocation();
From source file:com.reprezen.swagedit.model.NodeDeserializer.java
protected ArrayNode deserializeArrayNode(JsonParser p, DeserializationContext context, JsonLocation startLocation) throws IOException { final Model model = (Model) context.getAttribute(ATTRIBUTE_MODEL); final AbstractNode parent = (AbstractNode) context.getAttribute(ATTRIBUTE_PARENT); final JsonPointer ptr = (JsonPointer) context.getAttribute(ATTRIBUTE_POINTER); ArrayNode node = model.arrayNode(parent, ptr); int i = 0;/*from w ww . ja v a 2s. com*/ while (p.nextToken() != JsonToken.END_ARRAY) { JsonPointer pp = JsonPointer.compile(ptr.toString() + "/" + i); context.setAttribute(ATTRIBUTE_PARENT, node); context.setAttribute(ATTRIBUTE_POINTER, pp); AbstractNode v = deserialize(p, context); node.add(v); i++; } node.setStartLocation(createLocation(startLocation)); node.setEndLocation(createLocation(p.getCurrentLocation())); return node; }
From source file:com.cedarsoft.serialization.jackson.AbstractDelegatingJacksonSerializer.java
@Nonnull @Override// w w w . j a v a 2 s .c o m public T deserialize(@Nonnull JsonParser deserializeFrom, @Nonnull Version formatVersion) throws IOException, VersionException, JsonProcessingException { assert isVersionReadable(formatVersion); JacksonParserWrapper parserWrapper = new JacksonParserWrapper(deserializeFrom); parserWrapper.nextToken(); parserWrapper.verifyCurrentToken(JsonToken.FIELD_NAME); String currentName = parserWrapper.getCurrentName(); if (!PROPERTY_SUB_TYPE.equals(currentName)) { throw new JsonParseException( "Invalid field. Expected <" + PROPERTY_SUB_TYPE + "> but was <" + currentName + ">", parserWrapper.getCurrentLocation()); } parserWrapper.nextToken(); String type = deserializeFrom.getText(); if (type == null) { throw new JsonParseException("Attribute" + PROPERTY_SUB_TYPE + " not found. Cannot find strategy.", deserializeFrom.getCurrentLocation()); } SerializingStrategy<? extends T, JsonGenerator, JsonParser, JsonProcessingException, OutputStream, InputStream> strategy = serializingStrategySupport .findStrategy(type); Version resolvedVersion = serializingStrategySupport.resolveVersion(strategy, formatVersion); return strategy.deserialize(deserializeFrom, resolvedVersion); }
From source file:com.reprezen.swagedit.model.NodeDeserializer.java
protected ObjectNode deserializeObjectNode(JsonParser p, DeserializationContext context, JsonLocation startLocation) throws IllegalArgumentException, IOException { final Model model = (Model) context.getAttribute(ATTRIBUTE_MODEL); final AbstractNode parent = (AbstractNode) context.getAttribute(ATTRIBUTE_PARENT); final JsonPointer ptr = (JsonPointer) context.getAttribute(ATTRIBUTE_POINTER); final ObjectNode node = model.objectNode(parent, ptr); node.setStartLocation(createLocation(startLocation)); while (p.nextToken() != JsonToken.END_OBJECT) { String name = p.getCurrentName(); JsonPointer pp = JsonPointer.compile(ptr.toString() + "/" + name.replaceAll("/", "~1")); context.setAttribute(ATTRIBUTE_PARENT, node); context.setAttribute(ATTRIBUTE_POINTER, pp); AbstractNode v = deserialize(p, context); v.setProperty(name);// ww w . ja va 2s. c o m node.put(name, v); } node.setEndLocation(createLocation(p.getCurrentLocation())); return node; }
From source file:org.dswarm.graph.json.deserializer.ResourceDeserializer.java
@Override public Resource deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException { final ObjectCodec oc = jp.getCodec(); if (oc == null) { return null; }/*w w w .j a v a 2 s. c o m*/ final JsonNode node = oc.readTree(jp); if (node == null) { return null; } final Iterator<String> resourceUriFieldNames = node.fieldNames(); if (resourceUriFieldNames == null || !resourceUriFieldNames.hasNext()) { return null; } final String resourceUri = resourceUriFieldNames.next(); if (resourceUri == null) { return null; } final JsonNode resourceNode = node.get(resourceUri); if (resourceNode == null) { return null; } if (!ArrayNode.class.isInstance(resourceNode)) { throw new JsonParseException("expected a JSON array full of statement objects of the resource", jp.getCurrentLocation()); } final Resource resource = new Resource(resourceUri); if (resourceNode.size() <= 0) { return resource; } for (final JsonNode statementNode : resourceNode) { final Statement statement = statementNode.traverse(oc).readValueAs(Statement.class); resource.addStatement(statement); } return resource; }
From source file:org.dswarm.graph.json.deserializer.StatementDeserializer.java
@Override public Statement deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException { final ObjectCodec oc = jp.getCodec(); if (oc == null) { return null; }/*from ww w .j a v a 2 s . c o m*/ final JsonNode node = oc.readTree(jp); if (node == null) { return null; } final JsonNode idNode = node.get("id"); Long id = null; if (idNode != null) { try { id = idNode.asLong(); } catch (final Exception e) { id = null; } } final JsonNode uuidNode = node.get("uuid"); String uuid = null; if (uuidNode != null && JsonNodeType.NULL != uuidNode.getNodeType()) { uuid = uuidNode.asText(); } final JsonNode subjectNode = node.get("s"); if (subjectNode == null) { throw new JsonParseException("expected JSON node that represents the subject of a statement", jp.getCurrentLocation()); } final Node subject; if (subjectNode.get("uri") != null) { // resource node subject = subjectNode.traverse(oc).readValueAs(ResourceNode.class); } else { // bnode subject = subjectNode.traverse(oc).readValueAs(Node.class); } final JsonNode predicateNode = node.get("p"); if (predicateNode == null) { throw new JsonParseException("expected JSON node that represents the predicate of a statement", jp.getCurrentLocation()); } final Predicate predicate = predicateNode.traverse(oc).readValueAs(Predicate.class); final JsonNode objectNode = node.get("o"); if (objectNode == null) { throw new JsonParseException("expected JSON node that represents the object of a statement", jp.getCurrentLocation()); } final Node object; if (objectNode.get("uri") != null) { // resource node object = objectNode.traverse(oc).readValueAs(ResourceNode.class); } else if (objectNode.get("v") != null) { // literal node object = objectNode.traverse(oc).readValueAs(LiteralNode.class); } else { // bnode object = objectNode.traverse(oc).readValueAs(Node.class); } final JsonNode orderNode = node.get("order"); Long order = null; if (orderNode != null) { try { order = orderNode.asLong(); } catch (final Exception e) { order = null; } } final JsonNode evidenceNode = node.get("evidence"); String evidence = null; if (evidenceNode != null) { evidence = evidenceNode.asText(); } final JsonNode confidenceNode = node.get("confidence"); String confidence = null; if (confidenceNode != null) { confidence = confidenceNode.asText(); } final Statement statement = new Statement(subject, predicate, object); if (id != null) { statement.setId(id); } if (uuid != null) { statement.setUUID(uuid); } if (order != null) { statement.setOrder(order); } if (evidence != null) { statement.setEvidence(evidence); } if (confidence != null) { statement.setConfidence(confidence); } return statement; }
From source file:org.commonjava.maven.atlas.graph.jackson.ProjectRelationshipDeserializer.java
@Override public T deserialize(final JsonParser jp, final DeserializationContext ctx) throws JsonProcessingException, IOException { Map<String, Object> ast = new HashMap<String, Object>(); Map<String, JsonLocation> locations = new HashMap<String, JsonLocation>(); JsonToken token = jp.getCurrentToken(); String currentField = null;//from www. j a v a2s .co m List<String> currentArry = null; Logger logger = LoggerFactory.getLogger(getClass()); do { // logger.info( "Token: {}", token ); switch (token) { case START_ARRAY: { // logger.info( "Starting array for field: {}", currentField ); currentArry = new ArrayList<String>(); break; } case END_ARRAY: // logger.info( "Ending array for field: {}", currentField ); locations.put(currentField, jp.getCurrentLocation()); ast.put(currentField, currentArry); currentArry = null; break; case FIELD_NAME: currentField = jp.getCurrentName(); break; case VALUE_STRING: if (currentArry != null) { currentArry.add(jp.getText()); } else { locations.put(currentField, jp.getCurrentLocation()); ast.put(currentField, jp.getText()); } break; case VALUE_NUMBER_INT: locations.put(currentField, jp.getCurrentLocation()); ast.put(currentField, jp.getIntValue()); break; case VALUE_NUMBER_FLOAT: locations.put(currentField, jp.getCurrentLocation()); ast.put(currentField, jp.getFloatValue()); break; case VALUE_TRUE: locations.put(currentField, jp.getCurrentLocation()); ast.put(currentField, Boolean.TRUE); break; case VALUE_FALSE: locations.put(currentField, jp.getCurrentLocation()); ast.put(currentField, Boolean.FALSE); break; } token = jp.nextToken(); } while (token != JsonToken.END_OBJECT); StringBuilder sb = new StringBuilder(); sb.append("AST is:"); for (String field : ast.keySet()) { Object value = ast.get(field); sb.append("\n ").append(field).append(" = "); if (value == null) { sb.append("null"); } else { sb.append(value).append(" (type: ").append(value.getClass().getSimpleName()).append(")"); } } logger.debug(sb.toString()); final RelationshipType type = RelationshipType.getType((String) ast.get(RELATIONSHIP_TYPE)); final String uri = (String) ast.get(POM_LOCATION_URI); URI pomLocation; if (uri == null) { pomLocation = RelationshipUtils.POM_ROOT_URI; } else { try { pomLocation = new URI(uri); } catch (final URISyntaxException e) { throw new JsonParseException("Invalid " + POM_LOCATION_URI + ": '" + uri + "': " + e.getMessage(), locations.get(POM_LOCATION_URI), e); } } Collection<URI> sources = new HashSet<URI>(); List<String> srcs = (List<String>) ast.get(SOURCE_URIS); if (srcs != null) { for (String u : srcs) { try { sources.add(new URI(u)); } catch (URISyntaxException e) { throw new JsonParseException("Failed to parse source URI: " + u, locations.get(SOURCE_URIS)); } } } String decl = (String) ast.get(DECLARING_REF); final ProjectVersionRef declaring = SimpleProjectVersionRef.parse(decl); String tgt = (String) ast.get(TARGET_REF); Integer index = (Integer) ast.get(INDEX); if (index == null) { index = 0; } // handle null implicitly by comparing to true. boolean managed = Boolean.TRUE.equals(ast.get(MANAGED)); boolean inherited = Boolean.TRUE.equals(ast.get(INHERITED)); boolean mixin = Boolean.TRUE.equals(ast.get(MIXIN)); boolean optional = Boolean.TRUE.equals(ast.get(OPTIONAL)); ProjectRelationship<?, ?> rel = null; switch (type) { case DEPENDENCY: { final ArtifactRef target = SimpleArtifactRef.parse(tgt); String scp = (String) ast.get(SCOPE); final DependencyScope scope; if (scp == null) { scope = DependencyScope.compile; } else { scope = DependencyScope.getScope(scp); } rel = new SimpleDependencyRelationship(sources, pomLocation, declaring, target, scope, index, managed, inherited, optional); break; } case EXTENSION: { final ProjectVersionRef target = SimpleProjectVersionRef.parse(tgt); rel = new SimpleExtensionRelationship(sources, pomLocation, declaring, target, index, inherited); break; } case PARENT: { final ProjectVersionRef target = SimpleProjectVersionRef.parse(tgt); rel = new SimpleParentRelationship(sources, declaring, target); break; } case PLUGIN: { final ProjectVersionRef target = SimpleProjectVersionRef.parse(tgt); Boolean report = (Boolean) ast.get(REPORTING); rel = new SimplePluginRelationship(sources, pomLocation, declaring, target, index, managed, Boolean.TRUE.equals(report), inherited); break; } case PLUGIN_DEP: { String plug = (String) ast.get(PLUGIN_REF); if (plug == null) { throw new JsonParseException( "No plugin reference (field: " + PLUGIN_REF + ") found in plugin-dependency relationship!", jp.getCurrentLocation()); } final ProjectRef plugin = SimpleProjectRef.parse(plug); final ArtifactRef target = SimpleArtifactRef.parse(tgt); rel = new SimplePluginDependencyRelationship(sources, pomLocation, declaring, plugin, target, index, managed, inherited); break; } case BOM: { final ProjectVersionRef target = SimpleProjectVersionRef.parse(tgt); rel = new SimpleBomRelationship(sources, pomLocation, declaring, target, index, inherited, mixin); break; } } return (T) rel; }
From source file:de.fraunhofer.iosb.ilt.sta.deserialize.custom.CustomEntityDeserializer.java
@Override public T deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException, JsonProcessingException { Entity result;/*from w w w . j av a 2 s . co m*/ try { result = clazz.newInstance(); } catch (InstantiationException | IllegalAccessException ex) { throw new IOException("Error deserializing JSON!"); } // need to make subclass of this class for every Entity subclass with custom field to get expected class!!! BeanDescription beanDescription = ctxt.getConfig().introspect(ctxt.constructType(clazz)); ObjectMapper mapper = (ObjectMapper) parser.getCodec(); JsonNode obj = (JsonNode) mapper.readTree(parser); List<BeanPropertyDefinition> properties = beanDescription.findProperties(); Iterator<Map.Entry<String, JsonNode>> i = obj.fields(); // First check if we know all properties that are present. if (ctxt.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)) { for (; i.hasNext();) { Map.Entry<String, JsonNode> next = i.next(); String fieldName = next.getKey(); JsonNode field = next.getValue(); Optional<BeanPropertyDefinition> findFirst = properties.stream() .filter(p -> p.getName().equals(fieldName)).findFirst(); if (!findFirst.isPresent()) { throw new UnrecognizedPropertyException(parser, "Unknown field: " + fieldName, parser.getCurrentLocation(), clazz, fieldName, null); } } } for (BeanPropertyDefinition classProperty : properties) { if (obj.has(classProperty.getName())) { // property is present in class and json Annotation annotation = classProperty.getAccessor().getAnnotation(CustomSerialization.class); if (annotation != null) { // property has custom annotation // check if encoding property is also present in json (and also in class itself for sanity reasons) CustomSerialization customAnnotation = (CustomSerialization) annotation; Optional<BeanPropertyDefinition> encodingClassProperty = properties.stream() .filter(p -> p.getName().equals(customAnnotation.encoding())).findFirst(); if (!encodingClassProperty.isPresent()) { throw new IOException("Error deserializing JSON as class '" + clazz.toString() + "' \n" + "Reason: field '" + customAnnotation.encoding() + "' specified by annotation as encoding field is not defined in class!"); } String customEncoding = null; if (obj.has(customAnnotation.encoding())) { customEncoding = obj.get(customAnnotation.encoding()).asText(); } Object customDeserializedValue = CustomDeserializationManager.getInstance() .getDeserializer(customEncoding) .deserialize(mapper.writeValueAsString(obj.get(classProperty.getName()))); classProperty.getMutator().setValue(result, customDeserializedValue); } else { // TODO type identificatin is not safe beacuase may ne be backed by field. Rather do multiple checks Object value = mapper.readValue(mapper.writeValueAsString(obj.get(classProperty.getName())), classProperty.getField().getType()); classProperty.getMutator().setValue(result, value); } } } return (T) result; }
From source file:org.quantumbadger.redreader.jsonwrap.JsonValue.java
protected JsonValue(final JsonParser jp, final JsonToken firstToken) throws IOException { switch (firstToken) { case START_OBJECT: type = TYPE_OBJECT;//from w w w .j ava2 s . co m value = new JsonBufferedObject(); this.jp = jp; break; case START_ARRAY: type = TYPE_ARRAY; value = new JsonBufferedArray(); this.jp = jp; break; case VALUE_FALSE: type = TYPE_BOOLEAN; value = false; break; case VALUE_TRUE: type = TYPE_BOOLEAN; value = true; break; case VALUE_NULL: type = TYPE_NULL; value = null; break; case VALUE_STRING: type = TYPE_STRING; value = jp.getValueAsString(); break; case VALUE_NUMBER_FLOAT: //noinspection FloatingPointEquality,UnnecessaryExplicitNumericCast if (jp.getValueAsDouble() == (double) jp.getValueAsLong()) { type = TYPE_INTEGER; value = jp.getValueAsLong(); } else { type = TYPE_FLOAT; value = jp.getValueAsDouble(); } break; case VALUE_NUMBER_INT: type = TYPE_INTEGER; value = jp.getValueAsLong(); break; default: throw new JsonParseException("Expecting an object, literal, or array", jp.getCurrentLocation()); } }
From source file:com.ryan.ryanreader.jsonwrap.JsonValue.java
protected JsonValue(final JsonParser jp, final JsonToken firstToken) throws IOException { switch (firstToken) { case START_OBJECT: type = Type.OBJECT;// w w w . ja v a 2s .c om value = new JsonBufferedObject(); this.jp = jp; break; case START_ARRAY: type = Type.ARRAY; value = new JsonBufferedArray(); this.jp = jp; break; case VALUE_FALSE: type = Type.BOOLEAN; value = false; break; case VALUE_TRUE: type = Type.BOOLEAN; value = true; break; case VALUE_NULL: type = Type.NULL; value = null; break; case VALUE_STRING: type = Type.STRING; value = jp.getValueAsString(); break; case VALUE_NUMBER_FLOAT: //noinspection FloatingPointEquality,UnnecessaryExplicitNumericCast if (jp.getValueAsDouble() == (double) jp.getValueAsLong()) { type = Type.INTEGER; value = jp.getValueAsLong(); } else { type = Type.FLOAT; value = jp.getValueAsDouble(); } break; case VALUE_NUMBER_INT: type = Type.INTEGER; value = jp.getValueAsLong(); break; default: throw new JsonParseException("Expecting an object, literal, or array", jp.getCurrentLocation()); } }
From source file:timezra.dropbox.maven.plugin.client.DbxClientWrapper.java
private static <C> WithChildrenC<C> readWithNulls(final JsonParser parser, final Collector<DbxEntry, ? extends C> collector) throws IOException, JsonReadException { final JsonLocation top = JsonReader.expectObjectStart(parser); String size = null;/*from w w w. java2 s . c o m*/ long bytes = -1; String path = null; Boolean is_dir = null; Boolean is_deleted = null; String rev = null; Boolean thumb_exists = null; String icon = null; Date modified = null; Date client_mtime = null; String hash = null; C contents = null; while (parser.getCurrentToken() == JsonToken.FIELD_NAME) { final String fieldName = parser.getCurrentName(); JsonReader.nextToken(parser); final int fi = FM.get(fieldName); try { switch (fi) { case -1: JsonReader.skipValue(parser); break; case FM_size: size = JsonReader.StringReader.readField(parser, fieldName, size); break; case FM_bytes: bytes = JsonReader.readUnsignedLongField(parser, fieldName, bytes); break; case FM_path: path = JsonReader.StringReader.readField(parser, fieldName, path); break; case FM_is_dir: is_dir = JsonReader.BooleanReader.readField(parser, fieldName, is_dir); break; case FM_is_deleted: is_deleted = JsonReader.BooleanReader.readField(parser, fieldName, is_deleted); break; case FM_rev: rev = JsonReader.StringReader.readField(parser, fieldName, rev); break; case FM_thumb_exists: thumb_exists = JsonReader.BooleanReader.readField(parser, fieldName, thumb_exists); break; case FM_icon: icon = JsonReader.StringReader.readField(parser, fieldName, icon); break; case FM_modified: modified = JsonDateReader.Dropbox.readField(parser, fieldName, modified); break; case FM_client_mtime: client_mtime = JsonDateReader.Dropbox.readField(parser, fieldName, client_mtime); break; case FM_hash: if (collector == null) { throw new JsonReadException( "not expecting \"hash\" field, since we didn't ask for children", parser.getCurrentLocation()); } hash = JsonReader.StringReader.readField(parser, fieldName, hash); break; case FM_contents: if (collector == null) { throw new JsonReadException( "not expecting \"contents\" field, since we didn't ask for children", parser.getCurrentLocation()); } contents = JsonArrayReader.mk(Reader, collector).readField(parser, fieldName, contents); break; default: throw new AssertionError("bad index: " + fi + ", field = \"" + fieldName + "\""); } } catch (final JsonReadException ex) { throw ex.addFieldContext(fieldName); } } JsonReader.expectObjectEnd(parser); if (path == null) { throw new JsonReadException("missing field \"path\"", top); } if (icon == null) { throw new JsonReadException("missing field \"icon\"", top); } if (is_deleted == null) { is_deleted = Boolean.FALSE; } if (is_dir == null) { is_dir = Boolean.FALSE; } if (thumb_exists == null) { thumb_exists = Boolean.FALSE; } if (is_dir && (contents != null || hash != null)) { if (hash == null) { throw new JsonReadException("missing \"hash\", when we asked for children", top); } if (contents == null) { throw new JsonReadException("missing \"contents\", when we asked for children", top); } } DbxEntry e; if (is_dir) { e = new Folder(path, icon, thumb_exists); } else { // Normal File if (size == null) { throw new JsonReadException("missing \"size\" for a file entry", top); } if (bytes == -1) { throw new JsonReadException("missing \"bytes\" for a file entry", top); } if (modified == null) { throw new JsonReadException("missing \"modified\" for a file entry", top); } if (client_mtime == null) { throw new JsonReadException("missing \"client_mtime\" for a file entry", top); } if (rev == null) { throw new JsonReadException("missing \"rev\" for a file entry", top); } e = new File(path, icon, thumb_exists, bytes, size, modified, client_mtime, rev); } return new WithChildrenC<C>(e, hash, contents); }