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

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

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper 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.hybridbpm.core.util.HybridbpmCoreUtil.java

private static byte[] objectToJsonByteArray(Object object) {
    try {//from   w w  w.  ja v a 2 s  .c om
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.writeValue(baos, object);
        return baos.toByteArray();
    } catch (Exception ex) {
        logger.log(Level.SEVERE, ex.getMessage(), ex);
        throw new RuntimeException(ex);
    }
}

From source file:org.apache.nifi.toolkit.s2s.SiteToSiteCliMain.java

/**
 * Prints the usage to System.out//from ww  w .j  av  a 2 s  . c  o m
 *
 * @param errorMessage optional error message
 * @param options      the options object to print usage for
 */
public static void printUsage(String errorMessage, Options options) {
    if (errorMessage != null) {
        System.out.println(errorMessage);
        System.out.println();
        System.out.println();
    }
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    System.out.println(
            "s2s is a command line tool that can either read a list of DataPackets from stdin to send over site-to-site or write the received DataPackets to stdout");
    System.out.println();
    System.out.println(
            "The s2s cli input/output format is a JSON list of DataPackets.  They can have the following formats:");
    try {
        System.out.println();
        objectMapper.writeValue(System.out, Arrays.asList(
                new DataPacketDto("hello nifi".getBytes(StandardCharsets.UTF_8)).putAttribute("key", "value")));
        System.out.println();
        System.out.println(
                "Where data is the base64 encoded value of the FlowFile content (always used for received data) or");
        System.out.println();
        objectMapper.writeValue(System.out,
                Arrays.asList(new DataPacketDto(new HashMap<>(), new File("EXAMPLE").getAbsolutePath())
                        .putAttribute("key", "value")));
        System.out.println();
        System.out.println("Where dataFile is a file to read the FlowFile content from");
        System.out.println();
        System.out.println();
        System.out.println(
                "Example usage to send a FlowFile with the contents of \"hey nifi\" to a local unsecured NiFi over http with an input port named input:");
        System.out.print("echo '");
        DataPacketDto dataPacketDto = new DataPacketDto("hey nifi".getBytes(StandardCharsets.UTF_8));
        dataPacketDto.setAttributes(null);
        objectMapper.writeValue(System.out, Arrays.asList(dataPacketDto));
        System.out.println("' | bin/s2s.sh -n input -p http");
        System.out.println();
    } catch (IOException e) {
        e.printStackTrace();
    }
    HelpFormatter helpFormatter = new HelpFormatter();
    helpFormatter.setWidth(160);
    helpFormatter.printHelp("s2s", options);
    System.out.flush();
}

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

private static File createManifestJSONFile(final File tempPassDir, final ObjectMapper jsonObjectMapper)
        throws IOException, JsonGenerationException, JsonMappingException {
    Map<String, String> fileWithHashMap = new HashMap<String, String>();

    HashFunction hashFunction = Hashing.sha1();
    File[] filesInTempDir = tempPassDir.listFiles();
    hashFilesInDirectory(filesInTempDir, fileWithHashMap, hashFunction, null);
    File manifestJSONFile = new File(tempPassDir.getAbsolutePath() + File.separator + MANIFEST_JSON_FILE_NAME);
    jsonObjectMapper.writeValue(manifestJSONFile, fileWithHashMap);
    return manifestJSONFile;
}

From source file:parser.JsonWriter.java

/**
 * Creates json file for the cloudDSFPlus with all new attributes.
 * // w ww . java2s  .co  m
 * @param workbook
 * @throws JsonGenerationException
 * @throws JsonMappingException
 * @throws IOException
 */
private static void writeCloudDSFPlusJson(XSSFWorkbook workbook)
        throws JsonGenerationException, JsonMappingException, IOException {
    // instantiate parser for CloudDSFPlus and read excel
    CloudDSFPlusParser cloudDSFPlusParser = new CloudDSFPlusParser(workbook);
    CloudDSF cdsf = cloudDSFPlusParser.readExcel();
    // check the internal consistency and if successfull serialize data
    if (cdsf.checkSanity()) {
        // Helper Method
        // cdsf.printCloudDSF();
        // Jackson objectmapper and settings
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        // Ignore missing getters to serialize all values
        mapper.setVisibilityChecker(mapper.getSerializationConfig().getDefaultVisibilityChecker()
                .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
                .withGetterVisibility(JsonAutoDetect.Visibility.NONE));
        mapper.setSerializationInclusion(Include.NON_NULL);
        // create json structure
        JsonNode rootNode = mapper.createObjectNode();
        ((ObjectNode) rootNode).putPOJO("cdsfPlus", cdsf);
        ((ObjectNode) rootNode).putPOJO("links", cdsf.getInfluencingDecisions());
        ((ObjectNode) rootNode).putPOJO("outcomeLinks", cdsf.getInfluencingOutcomes());
        // Serialize CloudDSFPlus into json file
        File file = new File("cloudDSFPlus.json");
        mapper.writeValue(file, rootNode);
        System.out.println("Knowledge Base has been successfully verified and exported");
    } else {
        // knowledge base is not valid abort serialization
        System.out.println("The knowledge base is not valid");
    }
}

From source file:com.msopentech.odatajclient.testservice.utils.JSONUtilities.java

public static InputStream getJsonProperty(final InputStream src, final String[] path, final String edmType)
        throws Exception {

    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode srcNode = mapper.readTree(src);

    final ObjectNode property = new ObjectNode(JsonNodeFactory.instance);

    if (StringUtils.isNotBlank(edmType)) {
        property.put(JSON_ODATAMETADATA_NAME, ODATA_METADATA_PREFIX + edmType);
    }/*from w ww.  jav  a  2 s  .  c o  m*/

    JsonNode jsonNode = getJsonProperty(srcNode, path, 0);
    if (jsonNode.isObject()) {
        property.putAll((ObjectNode) jsonNode);
    } else {
        property.put("value", jsonNode.asText());
    }

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    mapper.writeValue(bos, property);

    final InputStream res = new ByteArrayInputStream(bos.toByteArray());
    IOUtils.closeQuietly(bos);

    return res;
}

From source file:com.antosara.akandaka.IO.java

public void write(EncryptedDatabase db) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(database, db);
}

From source file:ml.shifu.shifu.util.ColumnConfigTest.java

public void testSaveColumnConfig() throws JsonParseException, JsonMappingException, IOException {

    ColumnConfig[] configs = new ColumnConfig[5];
    for (int i = 0; i < 5; i++) {
        configs[i] = new ColumnConfig();
        configs[i].setColumnName("column" + i);
    }/*  w  w  w.ja  va2  s  .c om*/

    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(new File("src/test/resources/reason_data/test2.json"), configs);

}

From source file:mongofx.service.settings.SettingsService.java

public void save() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(new File(SETTINGS_FILE), settings);
}

From source file:com.mp3bot.JsonSink.java

public boolean handle(List<MediaInfo> medias) {
    ObjectMapper om = new ObjectMapper();
    try {//from  ww w  .  j a  v a  2s  . c  om
        om.writeValue(new File("result.json"), medias);
    } catch (IOException ex) {
        Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
    om = null;
    return true;
}

From source file:org.fusesource.restygwt.server.complex.DTOImplementationServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    DTOImplementation impl = new DTOImplementation();
    impl.setName("implementation");

    resp.setContentType("application/json");
    ObjectMapper om = new ObjectMapper();
    try {// w w  w  .j  ava  2  s .  c  o m
        om.writeValue(resp.getOutputStream(), impl);
    } catch (Exception e) {
        throw new ServletException(e);
    }
}