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:fll.web.ajax.DisplayQueryServlet.java

protected void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext application, final HttpSession session) throws IOException, ServletException {
    final String localDisplayPage;
    final String localDisplayURL;
    final String displayName = SessionAttributes.getAttribute(session, "displayName", String.class);
    if (displayName != null) {
        // update last seen time
        DisplayNames.appendDisplayName(application, session, displayName);

        final String myDisplayPage = ApplicationAttributes.getAttribute(application,
                displayName + "_displayPage", String.class);
        final String myDisplayURL = ApplicationAttributes.getAttribute(application, displayName + "_displayURL",
                String.class);

        localDisplayPage = myDisplayPage != null ? myDisplayPage
                : ApplicationAttributes.getAttribute(application, ApplicationAttributes.DISPLAY_PAGE,
                        String.class);

        localDisplayURL = myDisplayURL != null ? myDisplayURL
                : ApplicationAttributes.getAttribute(application, "displayURL", String.class);
    } else {/*from w  w w .ja  v a 2s. com*/
        localDisplayPage = ApplicationAttributes.getAttribute(application, ApplicationAttributes.DISPLAY_PAGE,
                String.class);
        localDisplayURL = ApplicationAttributes.getAttribute(application, "displayURL", String.class);
    }

    final String url = pickURL(request, localDisplayPage, localDisplayURL, application, session);
    final DisplayResponse displayResponse = new DisplayResponse(url);

    final ObjectMapper jsonMapper = new ObjectMapper();

    response.reset();
    response.setContentType("application/json");
    final PrintWriter writer = response.getWriter();

    jsonMapper.writeValue(writer, displayResponse);
}

From source file:org.comicwiki.Repository.java

public void save(OutputStream out, DataFormat format) throws Exception {
    if (DataFormat.JSON.equals(format)) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_DEFAULT);
        mapper.writeValue(out, cache.values());
    } else if (DataFormat.N_TRIPLES.equals(format)) {
        RDFDataset dataset = new RDFDataset();
        for (T t : cache.values()) {
            Collection<Statement> statements = ThingToStatementsTransformer.transform(t);

            for (Statement statement : statements) {
                dataset.addTriple(statement.getSubject().getValue(), statement.getPredicate().getValue(),
                        statement.getObject().getValue());
            }/*from w  w  w  .  j  av a  2 s.  c o m*/
        }
        out.write(RDFDatasetUtils.toNQuads(dataset).getBytes());
    } else if (DataFormat.TURTLE.equals(format)) {
        RDFDataset dataset = new RDFDataset();
        for (T t : cache.values()) {
            Collection<Statement> statements = ThingToStatementsTransformer.transform(t);

            for (Statement statement : statements) {
                dataset.addTriple(statement.getSubject().getValue(), statement.getPredicate().getValue(),
                        statement.getObject().getValue());
            }
        }
        Object output = JsonLdProcessor.fromRDF(RDFDatasetUtils.toNQuads(dataset));

        out.write(output.toString().getBytes());
    }
    out.close();
}

From source file:org.wildfly.swarm.plugin.fractionlist.FractionListMojo.java

protected void generateJSON(Set<FractionMetadata> fractions) {
    ObjectMapper mapper = new ObjectMapper();

    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    File outFile = new File(this.project.getBuild().getOutputDirectory(), "fraction-list.json");

    try {/*from   w  w  w  . ja v a2 s.  c  om*/
        mapper.writeValue(outFile, fractions);
    } catch (IOException e) {
        e.printStackTrace();
    }

    org.apache.maven.artifact.DefaultArtifact artifact = new org.apache.maven.artifact.DefaultArtifact(
            this.project.getGroupId(), this.project.getArtifactId(), this.project.getVersion(), "compile",
            "json", "", new DefaultArtifactHandler("json"));

    artifact.setFile(outFile);
    this.project.addAttachedArtifact(artifact);
}

From source file:mx.bigdata.anyobject.MapBasedAnyObject.java

public byte[] toJsonAsBytes() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {/* w  w w.  j  a  v a  2 s.c  o m*/
        mapper.writeValue(out, map);
        return out.toByteArray();
    } finally {
        out.close();
    }
}

From source file:mx.bigdata.anyobject.MapBasedAnyObject.java

public String toJson() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {/*from   ww  w .  j av  a2  s  .com*/
        mapper.writeValue(out, map);
        return out.toString();
    } finally {
        out.close();
    }
}

From source file:it.uniroma2.sag.kelp.linearization.nystrom.NystromMethodEnsemble.java

/**
 * Save an Ensemble of Nystrom projectors on file.
 * /*from w ww. ja  v  a2  s  .co  m*/
 * @param outputFilePath
 *            The output file name
 * @throws FileNotFoundException
 * @throws IOException
 */
public void save(String outputFilePath) throws FileNotFoundException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    OutputStream outputStream = FileUtils.createOutputStream(outputFilePath);
    mapper.writeValue(outputStream, this);
}

From source file:org.jboss.pnc.causeway.ImportedBuildJsonConversionIT.java

private String convertToJson(Object object) throws IOException {
    OutputStream stream = new ByteArrayOutputStream();
    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibilityChecker(mapper.getSerializationConfig().getDefaultVisibilityChecker()
            .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
            .withGetterVisibility(JsonAutoDetect.Visibility.NONE));

    mapper.writeValue(stream, object);
    stream.close();/*ww w. ja va 2  s .  c o m*/
    return stream.toString();
}

From source file:org.wikipedia.nirvana.nirvanabot.BotReporter.java

public void save(File file) {
    ObjectMapper mapper = new ObjectMapper();
    try {/*  w  w w.  ja v a  2  s.co m*/
        mapper.writeValue(file, reportItems);
    } catch (JsonParseException e) {
        log.error(e);
        return;
    } catch (JsonMappingException e) {
        log.error(e);
        return;
    } catch (IOException e) {
        log.error(e);
        return;
    }
    log.info("report items successfully saved to " + file.getPath());
}

From source file:org.roda.core.common.ClassificationPlanUtils.java

public static ConsumesOutputStream retrieveClassificationPlan(User user, String filename)
        throws RequestNotValidException, NotFoundException, GenericException, AuthorizationDeniedException {
    try {//w ww. ja v  a 2s .c  o m
        JsonFactory factory = new JsonFactory();
        ObjectMapper mapper = new ObjectMapper(factory);
        ObjectNode root = mapper.createObjectNode();

        ArrayNode array = mapper.createArrayNode();
        List<String> descriptionsLevels = RodaUtils.copyList(
                RodaCoreFactory.getRodaConfiguration().getList(RodaConstants.LEVELS_CLASSIFICATION_PLAN));

        Filter allButRepresentationsFilter = new Filter(
                new OneOfManyFilterParameter(RodaConstants.AIP_LEVEL, descriptionsLevels));

        IndexService index = RodaCoreFactory.getIndexService();
        boolean justActive = true;
        IterableIndexResult<IndexedAIP> res = index.findAll(IndexedAIP.class, allButRepresentationsFilter, null,
                Sublist.ALL, user, justActive, new ArrayList<>());
        Iterator<IndexedAIP> it = res.iterator();
        while (it.hasNext()) {
            array.add(aipToJSON(it.next()));
        }

        root.set("dos", array);
        return new ConsumesOutputStream() {

            @Override
            public void consumeOutputStream(OutputStream out) throws IOException {
                try {
                    mapper.writeValue(out, root);
                } catch (IOException e) {
                    throw e;
                } finally {
                    IOUtils.closeQuietly(out);
                }

            }

            @Override
            public String getFileName() {
                return filename;
            }

            @Override
            public String getMediaType() {
                return RodaConstants.MEDIA_TYPE_APPLICATION_JSON;
            }

        };
    } catch (IOException e) {
        throw new GenericException(e);
    }
}

From source file:com.foresee.date.AcsApiDateRange.java

public String ToAcsApiJson() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {/* w ww.ja  va 2  s .c  o  m*/
        mapper.writeValue(baos, this);
    } catch (Exception exc) {
        _logger.error("Failed to serialize object to json", exc);
        return null;
    }
    return baos.toString();
}