Example usage for com.fasterxml.jackson.core JsonParser readValueAs

List of usage examples for com.fasterxml.jackson.core JsonParser readValueAs

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonParser readValueAs.

Prototype

@SuppressWarnings("unchecked")
public <T> T readValueAs(TypeReference<?> valueTypeRef) throws IOException, JsonProcessingException 

Source Link

Document

Method to deserialize JSON content into a Java type, reference to which is passed as argument.

Usage

From source file:org.datagator.api.client.Entity.java

public static Entity create(Reader reader) throws IOException {
    JsonParser parser = json.createParser(reader);
    return parser.readValueAs(Entity.class);
}

From source file:com.amazonaws.services.dynamodbv2.datamodeling.DynamoDbPropertyMarshaller.java

public static <T extends Item> void setValue(final T item, final PropertyDescriptor propertyDescriptor,
        final AttributeValue attributeValue) {
    if (attributeValue != null) {
        final DynamoDBReflectorUtil reflector = new DynamoDBReflectorUtil();

        final Method writeMethod = propertyDescriptor.getWriteMethod();
        Object argument = null;//from   w w  w.  j av a2  s  .co m
        if (writeMethod != null) {
            try {
                final ArgumentUnmarshaller unmarshaller = reflector.getArgumentUnmarshaller(item,
                        propertyDescriptor.getReadMethod(), writeMethod, null);
                argument = unmarshaller.unmarshall(attributeValue);
            } catch (final DynamoDBMappingException | ParseException mappingException) {
                try {
                    final JsonParser jsonParser = jsonFactory
                            .createParser(new StringReader(attributeValue.getS()));
                    argument = jsonParser.readValueAs(writeMethod.getParameterTypes()[0]);
                } catch (final Exception e) {
                    throw new IllegalStateException("Could not parse attribute value: " + attributeValue, e);
                }
            }
            try {
                writeMethod.invoke(item, argument);
            } catch (final Exception e) {
                throw new IllegalStateException(e);
            }
        }
    }
}

From source file:org.agorava.linkedin.jackson.DeserializationUtils.java

public static <T> T deserializeFromDataNode(JsonParser jp, DeserializationContext ctxt, String propertyName,
        TypeReference<T> typeReference) throws IOException, JsonProcessingException {
    if (jp.hasCurrentToken() && jp.getCurrentToken().equals(JsonToken.START_OBJECT)) {
        JsonNode dataNode = jp.readValueAs(JsonNode.class);
        if (dataNode.has(propertyName)) {
            return OBJECT_MAPPER.reader(typeReference).<T>readValue(dataNode.get(propertyName));
        }//from  www  . ja  v  a2s. co  m
        return null;
    }
    throw ctxt.mappingException("Expected JSON object");
}

From source file:com.google.api.server.spi.config.annotationreader.ApiAnnotationIntrospector.java

private static <TFrom, TTo> JsonDeserializer<TFrom> getJsonDeserializer(
        @Nullable final Transformer<TFrom, TTo> serializer) {
    if (serializer == null) {
        return null;
    }/*from   www.  ja va  2 s  .  c o m*/
    final TypeReference<TTo> serializedType = typeReferenceOf(serializer);
    if (serializer instanceof ResourceTransformer) {
        @SuppressWarnings("unchecked")
        final ResourceTransformer<TFrom> resourceSerializer = (ResourceTransformer<TFrom>) serializer;
        return new ResourceDeserializer<>(resourceSerializer);
    } else {
        return new JsonDeserializer<TFrom>() {
            @Override
            public TFrom deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
                TTo deserialized = jp.readValueAs(serializedType);
                return serializer.transformFrom(deserialized);
            }
        };
    }
}

From source file:org.jberet.support.io.MongoItemReaderTest.java

static void addTestData(final String dataResource, final String mongoCollection, final int minSizeIfExists)
        throws Exception {
    final DBCollection collection = db.getCollection(mongoCollection);
    if (collection.find().count() >= minSizeIfExists) {
        System.out.printf("The readCollection %s already contains 100 items, skip adding test data.%n",
                mongoCollection);/*from   www  .  ja v a 2 s . c o  m*/
        return;
    }

    InputStream inputStream = MongoItemReaderTest.class.getClassLoader().getResourceAsStream(dataResource);
    if (inputStream == null) {
        try {
            final URL url = new URI(dataResource).toURL();
            inputStream = url.openStream();
        } catch (final Exception e) {
            System.out.printf("Failed to convert dataResource %s to URL: %s%n", dataResource, e);
        }
    }
    if (inputStream == null) {
        throw new IllegalStateException("The inputStream for the test data is null");
    }

    final JsonFactory jsonFactory = new MappingJsonFactory();
    final JsonParser parser = jsonFactory.createParser(inputStream);
    final JsonNode arrayNode = parser.readValueAs(ArrayNode.class);

    final Iterator<JsonNode> elements = arrayNode.elements();
    final List<DBObject> dbObjects = new ArrayList<DBObject>();
    while (elements.hasNext()) {
        final DBObject dbObject = (DBObject) JSON.parse(elements.next().toString());
        dbObjects.add(dbObject);
    }
    collection.insert(dbObjects);
}

From source file:org.mashti.jetson.util.JsonParserUtil.java

/**
 * Reads a field value as the provided type. This method supports parametrised types.
 *
 * @param parser the parser//from w w w  . j a  v a2  s .co m
 * @param expected_type the expected type of the value
 * @return the value
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static Object readValueAs(final JsonParser parser, final Type expected_type) throws IOException {

    final Object value;
    if (expected_type.equals(Void.TYPE)) {
        expectNullValue(parser);
        value = null;
    } else {
        parser.nextToken();
        value = parser.readValueAs(toTypeReference(expected_type));
    }
    return value;
}

From source file:org.mashti.jetson.util.JsonParserUtil.java

/**
 * Reads a field value as the provided type.
 *
 * @param <Value> the value type/*from   w  w w  . j a v a 2s.  c o m*/
 * @param parser the parser
 * @param expected_type the expected type of the value
 * @return the value
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static <Value> Value readValueAs(final JsonParser parser, final Class<Value> expected_type)
        throws IOException {

    final Value value;
    if (expected_type.equals(Void.TYPE)) {
        expectNullValue(parser);
        value = null;
    } else {
        parser.nextToken();
        value = parser.readValueAs(expected_type);
    }
    return value;
}

From source file:tachyon.master.EditLog.java

/**
 * Load one edit log.//from  ww w . j a va2  s .  c om
 * 
 * @param info The Master Info
 * @param path The path of the edit log
 * @throws IOException
 */
public static void loadSingleLog(MasterInfo info, String path) throws IOException {
    UnderFileSystem ufs = UnderFileSystem.get(path, info.getTachyonConf());

    DataInputStream is = new DataInputStream(ufs.open(path));
    JsonParser parser = JsonObject.createObjectMapper().getFactory().createParser(is);

    while (true) {
        EditLogOperation op;
        try {
            op = parser.readValueAs(EditLogOperation.class);
            LOG.debug("Read operation: {}", op);
        } catch (IOException e) {
            // Unfortunately brittle, but Jackson rethrows EOF with this message.
            if (e.getMessage().contains("end-of-input")) {
                break;
            } else {
                throw e;
            }
        }

        sCurrentTId = op.mTransId;
        try {
            switch (op.mType) {
            case ADD_BLOCK: {
                info.opAddBlock(op.getInt("fileId"), op.getInt("blockIndex"), op.getLong("blockLength"),
                        op.getLong("opTimeMs"));
                break;
            }
            case ADD_CHECKPOINT: {
                info._addCheckpoint(-1, op.getInt("fileId"), op.getLong("length"),
                        new TachyonURI(op.getString("path")), op.getLong("opTimeMs"));
                break;
            }
            case CREATE_FILE: {
                info._createFile(op.getBoolean("recursive"), new TachyonURI(op.getString("path")),
                        op.getBoolean("directory"), op.getLong("blockSizeByte"), op.getLong("creationTimeMs"));
                break;
            }
            case COMPLETE_FILE: {
                info._completeFile(op.get("fileId", Integer.class), op.getLong("opTimeMs"));
                break;
            }
            case SET_PINNED: {
                info._setPinned(op.getInt("fileId"), op.getBoolean("pinned"), op.getLong("opTimeMs"));
                break;
            }
            case RENAME: {
                info._rename(op.getInt("fileId"), new TachyonURI(op.getString("dstPath")),
                        op.getLong("opTimeMs"));
                break;
            }
            case DELETE: {
                info._delete(op.getInt("fileId"), op.getBoolean("recursive"), op.getLong("opTimeMs"));
                break;
            }
            case CREATE_RAW_TABLE: {
                info._createRawTable(op.getInt("tableId"), op.getInt("columns"), op.getByteBuffer("metadata"));
                break;
            }
            case UPDATE_RAW_TABLE_METADATA: {
                info.updateRawTableMetadata(op.getInt("tableId"), op.getByteBuffer("metadata"));
                break;
            }
            case CREATE_DEPENDENCY: {
                info._createDependency(op.get("parents", new TypeReference<List<Integer>>() {
                }), op.get("children", new TypeReference<List<Integer>>() {
                }), op.getString("commandPrefix"), op.getByteBufferList("data"), op.getString("comment"),
                        op.getString("framework"), op.getString("frameworkVersion"),
                        op.get("dependencyType", DependencyType.class), op.getInt("dependencyId"),
                        op.getLong("creationTimeMs"));
                break;
            }
            default:
                throw new IOException("Invalid op type " + op);
            }
        } catch (SuspectedFileSizeException e) {
            throw new IOException(e);
        } catch (BlockInfoException e) {
            throw new IOException(e);
        } catch (FileDoesNotExistException e) {
            throw new IOException(e);
        } catch (FileAlreadyExistException e) {
            throw new IOException(e);
        } catch (InvalidPathException e) {
            throw new IOException(e);
        } catch (TachyonException e) {
            throw new IOException(e);
        } catch (TableDoesNotExistException e) {
            throw new IOException(e);
        }
    }

    is.close();
    ufs.close();
}

From source file:tachyon.master.InodeFolder.java

/**
 * Create a new InodeFile from a JsonParser and an image Json element.
 *
 * @param parser the JsonParser to get the next element
 * @param ele the current InodeFolder's Json image element.
 * @return the constructed InodeFolder.//w w  w. j av a 2 s .co  m
 * @throws IOException
 */
static InodeFolder loadImage(JsonParser parser, ImageElement ele) throws IOException {
    final long creationTimeMs = ele.getLong("creationTimeMs");
    final int fileId = ele.getInt("id");
    final boolean isPinned = ele.getBoolean("pinned");
    final String fileName = ele.getString("name");
    final int parentId = ele.getInt("parentId");
    List<Integer> childrenIds = ele.get("childrenIds", new TypeReference<List<Integer>>() {
    });
    final long lastModificationTimeMs = ele.getLong("lastModificationTimeMs");
    int numberOfChildren = childrenIds.size();
    Inode[] children = new Inode[numberOfChildren];
    for (int k = 0; k < numberOfChildren; k++) {
        try {
            ele = parser.readValueAs(ImageElement.class);
            LOG.debug("Read Element: {}", ele);
        } catch (IOException e) {
            throw e;
        }

        switch (ele.mType) {
        case InodeFile: {
            children[k] = InodeFile.loadImage(ele);
            break;
        }
        case InodeFolder: {
            children[k] = InodeFolder.loadImage(parser, ele);
            break;
        }
        default:
            throw new IOException("Invalid element type " + ele);
        }
    }

    InodeFolder folder = new InodeFolder(fileName, fileId, parentId, creationTimeMs);
    folder.setPinned(isPinned);
    folder.addChildren(children);
    folder.setLastModificationTimeMs(lastModificationTimeMs);
    return folder;
}

From source file:ar.com.wolox.commons.base.json.DateTimeJsonDeserializer.java

@Override
public DateTime deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException {
    final String isoDateTime = jp.readValueAs(String.class);
    return ISODateTimeFormat.dateTime().parseDateTime(isoDateTime);
}