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

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

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:com.basistech.rosette.dm.json.array.JsonTest.java

@Test
public void versionInjected() throws Exception {
    StringWriter writer = new StringWriter();
    ObjectMapper mapper = AnnotatedDataModelArrayModule.setupObjectMapper(new ObjectMapper());
    ObjectWriter objectWriter = mapper.writer();
    objectWriter.writeValue(writer, referenceText);
    // to tell that the version is there, we read as a tree
    JsonNode tree = mapper.readTree(writer.toString());
    assertEquals("1.1.0", tree.get(4).asText());
}

From source file:com.proofpoint.jaxrs.JsonMapper.java

@Override
public void writeTo(Object value, Class<?> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream outputStream)
        throws IOException {
    // Prevent broken browser from attempting to render the json as html
    httpHeaders.add(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff");

    JsonFactory jsonFactory = objectMapper.getFactory();
    jsonFactory.setCharacterEscapes(HTMLCharacterEscapes.INSTANCE);

    JsonGenerator jsonGenerator = jsonFactory.createGenerator(outputStream, JsonEncoding.UTF8);

    // Important: we are NOT to close the underlying stream after
    // mapping, so we need to instruct generator:
    jsonGenerator.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);

    // Pretty print?
    if (isPrettyPrintRequested()) {
        jsonGenerator.useDefaultPrettyPrinter();
    }/*  w  w w  .  j  a  va2  s. c o  m*/

    // 04-Mar-2010, tatu: How about type we were given? (if any)
    JavaType rootType = null;
    if (genericType != null && value != null) {
        // 10-Jan-2011, tatu: as per [JACKSON-456], it's not safe to just force root
        //    type since it prevents polymorphic type serialization. Since we really
        //    just need this for generics, let's only use generic type if it's truly
        //    generic.
        if (genericType.getClass() != Class.class) { // generic types are other implementations of 'java.lang.reflect.Type'
            // This is still not exactly right; should root type be further
            // specialized with 'value.getClass()'? Let's see how well this works before
            // trying to come up with more complete solution.
            rootType = objectMapper.getTypeFactory().constructType(genericType);
            // 26-Feb-2011, tatu: To help with [JACKSON-518], we better recognize cases where
            //    type degenerates back into "Object.class" (as is the case with plain TypeVariable,
            //    for example), and not use that.
            //
            if (rootType.getRawClass() == Object.class) {
                rootType = null;
            }
        }
    }

    ObjectWriter writer;
    if (rootType != null) {
        writer = objectMapper.writerWithType(rootType);
    } else {
        writer = objectMapper.writer();
    }

    writer.writeValue(jsonGenerator, value);

    // add a newline so when you use curl it looks nice
    outputStream.write('\n');
}

From source file:de.raion.xmppbot.XmppContext.java

/**
 * saves the given Object via Jackson Object Mapper as json file in the
 * working directory of the XmppBot.<br>
 * example: if the objects class is <code>MyConfig.class</code> and the workingdir is
 * <code>xmppbot/config/</code>, then the context tries to save the configuration to
 * the file <code>xmppbot/config/myconfig.json</code>
 * @param config the Object to save//from w w w  .j a va  2 s .  c om
 * @throws IOException if IOException occure
 */
public void saveConfig(Object config) throws IOException {

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

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

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

}

From source file:com.neoteric.starter.metrics.report.elastic.ElasticsearchReporter.java

private void writeJsonMetric(JsonMetric jsonMetric, ObjectWriter writer, OutputStream out) throws IOException {
    writer.writeValue(out,
            new MetricsElasticsearchModule.BulkIndexOperationHeader(currentIndexName, jsonMetric.type()));
    out.write("\n".getBytes());
    writer.writeValue(out, jsonMetric);/* w  w w  . j  ava  2 s.c om*/
    out.write("\n".getBytes());

    out.flush();
}

From source file:io.airlift.jaxrs.JsonMapper.java

@Override
public void writeTo(Object value, Class<?> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream outputStream)
        throws IOException {
    // Prevent broken browser from attempting to render the json as html
    httpHeaders.add(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff");

    JsonFactory jsonFactory = objectMapper.getJsonFactory();
    jsonFactory.setCharacterEscapes(HTMLCharacterEscapes.INSTANCE);

    JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(outputStream, JsonEncoding.UTF8);

    // Important: we are NOT to close the underlying stream after
    // mapping, so we need to instruct generator:
    jsonGenerator.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);

    // Pretty print?
    if (isPrettyPrintRequested()) {
        jsonGenerator.useDefaultPrettyPrinter();
    }//w w  w .  j a  v a  2s.  co m

    // 04-Mar-2010, tatu: How about type we were given? (if any)
    JavaType rootType = null;
    if (genericType != null && value != null) {
        // 10-Jan-2011, tatu: as per [JACKSON-456], it's not safe to just force root
        //    type since it prevents polymorphic type serialization. Since we really
        //    just need this for generics, let's only use generic type if it's truly
        //    generic.
        if (genericType.getClass() != Class.class) { // generic types are other implementations of 'java.lang.reflect.Type'
            // This is still not exactly right; should root type be further
            // specialized with 'value.getClass()'? Let's see how well this works before
            // trying to come up with more complete solution.
            rootType = objectMapper.getTypeFactory().constructType(genericType);
            // 26-Feb-2011, tatu: To help with [JACKSON-518], we better recognize cases where
            //    type degenerates back into "Object.class" (as is the case with plain TypeVariable,
            //    for example), and not use that.
            //
            if (rootType.getRawClass() == Object.class) {
                rootType = null;
            }
        }
    }

    String jsonpFunctionName = getJsonpFunctionName();
    if (jsonpFunctionName != null) {
        value = new JSONPObject(jsonpFunctionName, value, rootType);
        rootType = null;
    }

    ObjectWriter writer;
    if (rootType != null) {
        writer = objectMapper.writerWithType(rootType);
    } else {
        writer = objectMapper.writer();
    }

    writer.writeValue(jsonGenerator, value);

    // add a newline so when you use curl it looks nice
    outputStream.write('\n');
}

From source file:com.oneops.metrics.es.ElasticsearchReporter.java

/**
 * serialize a JSON metric over the outputstream in a bulk request
 *//*w  ww.j  a va  2s. c  o m*/
private void writeJsonMetric(JsonMetric jsonMetric, ObjectWriter writer, OutputStream out) throws IOException {
    writer.writeValue(out, new BulkIndexOperationHeader(currentIndexName, jsonMetric.type()));
    out.write("\n".getBytes());
    writer.writeValue(out, jsonMetric);
    out.write("\n".getBytes());

    out.flush();
}

From source file:org.usd.edu.btl.cli.ConvertBets.java

public void toBld(String inputS, String output) {
    ObjectMapper mapper = new ObjectMapper(); //create new Jackson Mapper
    File input = new File(inputS);
    //mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); //ignore the extra BETS fields
    BETSV1 betsTool;/*from   w w w. j  a  va 2 s  .  co  m*/

    try {
        //map input json files to iplant class
        betsTool = mapper.readValue(input, BETSV1.class);

        //convert bets to BioExtract
        BLDV1 bExtOutput = BETSConverter.toBld(betsTool); //pass the iplant tool spec, convert to bets

        ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();

        if (output == null) {
            /*===============PRINT JSON TO CONSOLE AND FILES =================== */
            ObjectWriter bExtWriter = mapper.writer().withDefaultPrettyPrinter();
            String bExtJson = bExtWriter.writeValueAsString(bExtOutput); //write Json as String

            System.err.println("=== BETS TO BLD JSON === \n");
            System.out.println(bExtJson);
        } else {
            //write to files
            ow.writeValue(new File(output), bExtOutput);
            System.err.println(output + " has been created successfully");
        }
    } catch (IOException e) {
        System.err.println(e.getMessage());
    }
}

From source file:org.usd.edu.btl.cli.ConvertBets.java

public void toSeq(String inputS, String output) {
    ObjectMapper mapper = new ObjectMapper(); //create new Jackson Mapper
    File input = new File(inputS);

    //mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); //ignore the extra BETS fields
    BETSV1 betsTool;/*from   w  ww .j  a va 2s. co  m*/

    try {
        //map input json files to iplant class
        betsTool = mapper.readValue(input, BETSV1.class);

        //convert bets to BioExtract
        SeqV1 bExtOutput = BETSConverter.toSeq(betsTool); //pass the iplant tool spec, convert to bets

        ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();

        if (output == null) {
            /*===============PRINT JSON TO CONSOLE AND FILES =================== */
            ObjectWriter bExtWriter = mapper.writer().withDefaultPrettyPrinter();
            String bExtJson = bExtWriter.writeValueAsString(bExtOutput); //write Json as String

            System.err.println("=== BETS TO SEQ JSON === \n");
            System.out.println(bExtJson);
        } else {
            //write to files
            ow.writeValue(new File(output), bExtOutput);
            System.err.println(output + " has been created successfully");
        }
    } catch (IOException e) {
        System.err.println(e.getMessage());
    }
}

From source file:org.usd.edu.btl.cli.ConvertBets.java

public void toBioextract(String inputS, String output) {
    ObjectMapper mapper = new ObjectMapper(); //create new Jackson Mapper
    File input = new File(inputS);

    //mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); //ignore the extra BETS fields
    BETSV1 betsTool;//from  w w  w .  j  a va  2s  .co m

    try {
        //map input json files to iplant class
        betsTool = mapper.readValue(input, BETSV1.class);

        //convert bets to BioExtract
        BioExtV1 bExtOutput = BETSConverter.toBioExtract(betsTool); //pass the iplant tool spec, convert to bets
        ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();

        if (output == null) {
            /*===============PRINT JSON TO CONSOLE AND FILES =================== */
            ObjectWriter bExtWriter = mapper.writer().withDefaultPrettyPrinter();
            String bExtJson = bExtWriter.writeValueAsString(bExtOutput); //write Json as String

            System.err.println("=== BETS TO BioExtract JSON === \n");
            System.out.println(bExtJson);
        } else {
            //write to files
            ow.writeValue(new File(output), bExtOutput);
            System.err.println(output + " has been created successfully");
        }
    } catch (IOException e) {
        System.err.println(e.getMessage());
    }
}