Example usage for com.fasterxml.jackson.databind ObjectWriter writeValue

List of usage examples for com.fasterxml.jackson.databind ObjectWriter writeValue


In this page you can find the example usage for com.fasterxml.jackson.databind ObjectWriter writeValue.


public void writeValue(Writer w, Object value)
        throws IOException, JsonGenerationException, JsonMappingException 

Source Link


Method that can be used to serialize any Java value as JSON output, using Writer provided.


From source file:de.raion.xmppbot.hipchat.HipChatAPIConfig.java

public static void main(String[] args) throws Exception {
    HipChatAPIConfig config = new HipChatAPIConfig();
    config.setBaseURL(new URL("https://api.hipchat.com"));

    ObjectWriter writer = new ObjectMapper().writerWithDefaultPrettyPrinter();

    String filename = config.getClass().getSimpleName().toLowerCase() + ".json";

    writer.writeValue(new File(filename), config);

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

 * Writes the given {@code values} as a JSON array with the given field name and serialises each value as a provided type.
 * An {@link ObjectMapper} must be present as the {@code generator}'s {@link JsonGenerator#getCodec() codec}.
 * For each value in the given {@code values}, a type must be provided under the same index in {@code value_types}.
 * This method supports parameterised types.
 * @param generator the JSON generator/*from   w w  w . j ava  2 s  . co  m*/
 * @param field_name the field name of the JSON array
 * @param value_types the types of the values
 * @param values the values
 * @throws IOException Signals that an I/O exception has occurred.
public static void writeValuesAs(final JsonGenerator generator, final String field_name,
        final Type[] value_types, final Object[] values) throws IOException {

    if (values != null && values.length > 0) {
        final ObjectMapper mapper = (ObjectMapper) generator.getCodec();
        int i = 0;
        for (final Object value : values) {
            final Type value_type = value_types[i++];
            final ObjectWriter writer = mapper.writerWithType(JsonParserUtil.toTypeReference(value_type));
            writer.writeValue(generator, value);

From source file:net.arp7.HdfsPerfTest.WriteFile.java

private static void writeCsvResult(final FileIoStats stats) {
    if (params.getResultCsvFile() == null) {
        return;//from www.  j  a va  2 s .  c o  m

    final Object[] results = new Object[] { new Date().toGMTString(), params.getNumFiles(),
            params.getNumThreads(), params.getReplication(), params.getBlockSize(), params.getIoSize(),
            stats.getFilesWritten(), stats.getBytesWritten(), stats.getMeanCreateTimeMs(),
            stats.getMeanWriteTimeMs(), stats.getMeanCloseTimeMs(), stats.getElapsedTimeMs(),
            (params.getFileSize() * 1000) / stats.getElapsedTimeMs(),
            (params.getNumFiles() * params.getFileSize() * 1000) / stats.getElapsedTimeMs(), params.getNote() };

    final CsvSchema schema = CsvSchema.builder().setColumnSeparator(';').setQuoteChar('"')
            .addColumn("timestamp", CsvSchema.ColumnType.STRING)
            .addColumn("number of files", CsvSchema.ColumnType.NUMBER)
            .addColumn("number of threads", CsvSchema.ColumnType.NUMBER)
            .addColumn("replication factor", CsvSchema.ColumnType.NUMBER)
            .addColumn("block size", CsvSchema.ColumnType.NUMBER)
            .addColumn("io size", CsvSchema.ColumnType.NUMBER)
            .addColumn("total files written", CsvSchema.ColumnType.NUMBER)
            .addColumn("total bytes written", CsvSchema.ColumnType.NUMBER)
            .addColumn("mean time to create file in ms", CsvSchema.ColumnType.NUMBER)
            .addColumn("mean time to write file in ms", CsvSchema.ColumnType.NUMBER)
            .addColumn("mean time to close file in ms", CsvSchema.ColumnType.NUMBER)
            .addColumn("total ms", CsvSchema.ColumnType.NUMBER)
            .addColumn("mean throughput bytes per s", CsvSchema.ColumnType.NUMBER)
            .addColumn("aggregate throughput bytes per s", CsvSchema.ColumnType.NUMBER)
            .addColumn("note", CsvSchema.ColumnType.STRING).build();

    try (FileWriter fileWriter = new FileWriter(params.getResultCsvFile(), true)) {
        final CsvMapper mapper = new CsvMapper();
        final ObjectWriter writer = mapper.writer(schema);
        writer.writeValue(fileWriter, results);
    } catch (IOException e) {
        LOG.error("Could not write results to CSV file '{}': '{}'", params.getResultCsvFile().getPath(),

From source file:hrytsenko.csv.IO.java

 * Saves records into CSV file./*  w  w  w  . j ava2 s  . c o  m*/
 * <p>
 * If file already exists, then it will be overridden.
 * @param args
 *            the named arguments {@link IO}.
 * @throws IOException
 *             if file could not be written.
public static void save(Map<String, ?> args) throws IOException {
    Path path = getPath(args);
    LOGGER.info("Save: {}.", path.getFileName());

    Collection<Record> records = (Collection<Record>) args.get("records");
    if (records.isEmpty()) {
        LOGGER.info("No records to save.");

    try (Writer dataWriter = newBufferedWriter(path, getCharset(args), StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING)) {
        Set<String> columns = new LinkedHashSet<>();
        List<Map<String, String>> rows = new ArrayList<>();
        for (Record record : records) {
            Map<String, String> values = record.values();

        CsvSchema.Builder csvSchema = getSchema(args).setUseHeader(true);
        for (String column : columns) {
        CsvMapper csvMapper = new CsvMapper();
        ObjectWriter csvWriter = csvMapper.writer().withSchema(csvSchema.build());
        csvWriter.writeValue(dataWriter, rows);

From source file:de.brendamour.jpasskit.signing.PKSigningUtil.java

private static void createPassJSONFile(final PKPass pass, final File tempPassDir,
        final ObjectMapper jsonObjectMapper) throws IOException, JsonGenerationException, JsonMappingException {
    File passJSONFile = new File(tempPassDir.getAbsolutePath() + File.separator + PASS_JSON_FILE_NAME);

    SimpleFilterProvider filters = new SimpleFilterProvider();

    // haven't found out, how to stack filters. Copying the validation one for now.
            SimpleBeanPropertyFilter.serializeAllExcept("valid", "validationErrors"));
    filters.addFilter("pkPassFilter", SimpleBeanPropertyFilter.serializeAllExcept("valid", "validationErrors",
            "foregroundColorAsObject", "backgroundColorAsObject", "labelColorAsObject"));
    filters.addFilter("barcodeFilter", SimpleBeanPropertyFilter.serializeAllExcept("valid", "validationErrors",
    filters.addFilter("charsetFilter", SimpleBeanPropertyFilter.filterOutAllExcept("name"));
    jsonObjectMapper.addMixInAnnotations(Object.class, ValidateFilterMixIn.class);
    jsonObjectMapper.addMixInAnnotations(PKPass.class, PkPassFilterMixIn.class);
    jsonObjectMapper.addMixInAnnotations(PKBarcode.class, BarcodeFilterMixIn.class);
    jsonObjectMapper.addMixInAnnotations(Charset.class, CharsetFilterMixIn.class);

    ObjectWriter objectWriter = jsonObjectMapper.writer(filters);
    objectWriter.writeValue(passJSONFile, pass);

From source file:tachyon.master.ImageWriter.java

 * Write an ImageElement to the specified DataOutputStream. Use the specified ObjectWriter.
 * // w w  w  .j a v  a2  s  .  com
 * @param objWriter The used object writer
 * @param dos The target data output stream
 * @param ele The image element to be written
protected void writeElement(ObjectWriter objWriter, DataOutputStream dos, ImageElement ele) {
    try {
        objWriter.writeValue(dos, ele);
    } catch (IOException e) {
        throw Throwables.propagate(e);

From source file:com.infinities.skyport.compute.entity.serializer.ShortSelfRecursiveSerializer.java

public void serialize(Serializable value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonGenerationException {

    ObjectMapper mapper = JsonUtil.getObjectMapper();

    ObjectWriter writer = mapper.writerWithView(Views.Short.class);
    StringWriter sw = new StringWriter();
    writer.writeValue(sw, value);

    JsonNode rootNode = mapper.readTree(sw.toString());

    jgen.writeObject(rootNode);/*from  ww w.  j ava 2s. c o  m*/


From source file:com.infinities.skyport.compute.entity.serializer.BasicSelfRecursiveSerializer.java

public void serialize(Collection<?> value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonGenerationException {

    ObjectMapper mapper = JsonUtil.getObjectMapper();

    ObjectWriter writer = mapper.writerWithView(Views.Basic.class);
    StringWriter sw = new StringWriter();
    writer.writeValue(sw, value);

    JsonNode rootNode = mapper.readTree(sw.toString());

    jgen.writeObject(rootNode);/*from   ww  w  .ja v  a  2  s .  c  om*/


From source file:com.heisenberg.impl.json.JacksonJsonService.java

protected void objectToJson(Object object, Writer writer, ObjectWriter objectWriter) {
    try {//from ww w. ja v a 2 s .com
        objectWriter.writeValue(writer, object);
    } catch (IOException e) {
        throw new RuntimeException(e);

From source file:br.com.ingenieux.mojo.simpledb.cmd.DumpDomainCommand.java

private void writeData(JsonNode rootNode, Writer fileWriter) throws Exception {
    ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();

    writer.writeValue(fileWriter, rootNode);