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:net.hamnaberg.json.Template.java

public void writeTo(Writer writer) throws IOException {
    ObjectMapper factory = new ObjectMapper();
    ObjectNode template = JsonNodeFactory.instance.objectNode();
    template.set("template", asJson());
    factory.writeValue(writer, template);
}

From source file:nl.ortecfinance.opal.jacksonweb.IncomePlanningSimulationRequestTest.java

@Test
public void testSerializeDate() throws IOException {

    IncomePlanningSimulationRequest req = new IncomePlanningSimulationRequest();
    final Date today = DateUtils.createDate(2015, 4);
    final Date dobLieve = DateUtils.createDate(2008, 8, 24);
    req.setStartPeriod(today);//ww  w  .  j av a 2  s .  c  om
    req.setDob(dobLieve);
    req.setProcessingDate(today);

    System.out.println("today:" + today);
    System.out.println("Lieve:" + dobLieve);

    StringWriter sw = new StringWriter();
    ObjectMapper m = new ObjectMapper();
    m.writeValue(sw, req);

    String json = sw.toString();
    System.out.println("testSerializeDate:" + json);

    StringReader sr = new StringReader(json);
    m.enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES);
    IncomePlanningSimulationRequest reqReadBack = m.readValue(sr, IncomePlanningSimulationRequest.class);

    Assert.assertEquals(dobLieve, reqReadBack.getDob());
    Assert.assertEquals(today, reqReadBack.getStartPeriod());

}

From source file:com.dataartisans.flink.dataflow.translation.functions.FlinkDoFnFunction.java

private void writeObject(ObjectOutputStream out) throws IOException, ClassNotFoundException {
    out.defaultWriteObject();/*from   w  ww  . j av a  2  s . c o m*/
    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(out, options);
}

From source file:com.ponysdk.mongodb.dao.MongoDAO.java

private void saveOrUpdate(final Object object, final String nameSpace) {
    final ObjectMapper mapper = new ObjectMapper();
    final StringWriter jsonOutput = new StringWriter();
    try {//from  w  w  w . ja va2s .  co m
        mapper.writeValue(jsonOutput, object);
        final DBObject dbObject = (DBObject) JSON.parse(jsonOutput.toString());
        final Identifiable m = (Identifiable) object;
        if (m.getID() != null) {
            db.getCollection(nameSpace).findAndModify(new BasicDBObject("_id", m.getID()), dbObject);
        } else {
            final ObjectId id = new ObjectId();
            dbObject.put("_id", id);
            db.getCollection(nameSpace).save(dbObject);
            m.setID(id);
        }
    } catch (final Exception e) {
        e.printStackTrace();
    }
}

From source file:org.broadleafcommerce.core.web.processor.ProductOptionValueProcessor.java

@Override
protected ProcessorResult processAttribute(Arguments arguments, Element element, String attributeName) {

    Expression expression = (Expression) StandardExpressions.getExpressionParser(arguments.getConfiguration())
            .parseExpression(arguments.getConfiguration(), arguments, element.getAttributeValue(attributeName));
    ProductOptionValue productOptionValue = (ProductOptionValue) expression
            .execute(arguments.getConfiguration(), arguments);

    ProductOptionValueDTO dto = new ProductOptionValueDTO();
    dto.setOptionId(productOptionValue.getProductOption().getId());
    dto.setValueId(productOptionValue.getId());
    dto.setValueName(productOptionValue.getAttributeValue());
    if (productOptionValue.getPriceAdjustment() != null) {
        dto.setPriceAdjustment(productOptionValue.getPriceAdjustment().getAmount());
    }/*from   ww w .ja  v  a2 s  .c o m*/
    try {
        ObjectMapper mapper = new ObjectMapper();
        Writer strWriter = new StringWriter();
        mapper.writeValue(strWriter, dto);
        element.setAttribute("data-product-option-value", strWriter.toString());
        element.removeAttribute(attributeName);
        return ProcessorResult.OK;
    } catch (Exception ex) {
        LOG.error("There was a problem writing the product option value to JSON", ex);
    }

    return null;

}

From source file:fll.web.api.ChallengeDescriptionServlet.java

@Override
protected final void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException, ServletException {
    final ServletContext application = getServletContext();

    response.reset();/*from  w ww  . j av  a  2 s.co m*/
    response.setContentType("application/json");
    final PrintWriter writer = response.getWriter();

    final ObjectMapper jsonMapper = new ObjectMapper();

    final ChallengeDescription challengeDescription = ApplicationAttributes
            .getChallengeDescription(application);

    jsonMapper.writeValue(writer, challengeDescription);
}

From source file:com.irccloud.android.IRCCloudJSONObject.java

public String toString() {
    ObjectMapper mapper = new ObjectMapper();
    StringWriter writer = new StringWriter();
    try {/*  w w w .  ja va2  s . c  o  m*/
        mapper.writeValue(writer, o);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return writer.toString();
}

From source file:parser.JsonWriter.java

/**
 * Generates json file for the CloudDSF avoiding any unnecessary attribute serialization.
 * // www  .jav  a2s.  c  om
 * @param workbook
 * @throws JsonGenerationException
 * @throws JsonMappingException
 * @throws IOException
 */
private static void writeCloudDSFJson(XSSFWorkbook workbook)
        throws JsonGenerationException, JsonMappingException, IOException {
    // Instantiate parser to parse file for CloudDSF
    CloudDSFParser parser = new CloudDSFParser(workbook);
    // CloudDSF object representing all necessary information
    CloudDSF cdsf = parser.readExcel();
    // Helper Method to check content
    // cdsf.printCloudDSF();
    // Create task tree for legacy visualizations
    TaskTree taskTree = new TaskTree();
    taskTree.setTasks(cdsf.getTasks());

    // Jackson objectmapper and settings
    ObjectMapper mapper = new ObjectMapper();
    // Pretty Print
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    // If getter is found values will be serialized avoiding unnecessary attributes
    mapper.setVisibilityChecker(mapper.getSerializationConfig().getDefaultVisibilityChecker()
            .withFieldVisibility(JsonAutoDetect.Visibility.DEFAULT)
            .withGetterVisibility(JsonAutoDetect.Visibility.DEFAULT));
    // Ignore fields with null values to avoid serialization of empty lists
    mapper.setSerializationInclusion(Include.NON_NULL);
    // Write all relations into one list to conform to legacy implementation
    cdsf.setInfluencingRelations();
    // create json root node and add json objects
    JsonNode rootNode = mapper.createObjectNode();
    ((ObjectNode) rootNode).putPOJO("decisionTree", cdsf);
    ((ObjectNode) rootNode).putPOJO("taskTree", taskTree);
    ((ObjectNode) rootNode).putPOJO("linksArray", cdsf.getInfluencingRelations());
    // serialize CloudDSF into file
    File file = new File("cloudDSF.json");
    mapper.writeValue(file, rootNode);
}

From source file:ijfx.service.overlay.io.OverlaySaver.java

public void save(List<? extends Overlay> overlays, File file) throws IOException {

    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addSerializer(Overlay.class, new OverlaySerializer());
    mapper.registerModule(module);/*from   w w w. j  a  v a 2  s.c o m*/

    mapper.writeValue(file, overlays);

}

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

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    DTOCustom1 one = new DTOCustom1();
    one.name = "Fred Flintstone";
    one.size = 1024;/* w  w  w  . j  a  v  a 2 s . c o  m*/

    DTOCustom2 two = new DTOCustom2();
    two.name = "Barney Rubble";
    two.foo = "schmaltzy";

    DTOCustom2 three = new DTOCustom2();
    three.name = "BamBam Rubble";
    three.foo = "dorky";

    resp.setContentType("application/json");
    ObjectMapper om = new ObjectMapper();
    try {
        AbstractCustomDtoList list = new AbstractCustomDtoList(Lists.newArrayList(one, two, three));
        om.writeValue(resp.getOutputStream(), list);
    } catch (Exception e) {
        throw new ServletException(e);
    }
}