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

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

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper enable.

Prototype

public ObjectMapper enable(SerializationFeature f) 

Source Link

Document

Method for enabling specified DeserializationConfig feature.

Usage

From source file:org.smartdeveloperhub.vocabulary.config.ConfigurationFactory.java

private static ObjectMapper writingMapper() {
    final YAMLFactory factory = yamlFactory();
    factory.enable(JsonGenerator.Feature.ESCAPE_NON_ASCII);
    final ObjectMapper mapper = new ObjectMapper(factory);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    return mapper;
}

From source file:io.fouad.jtb.core.utils.JsonUtils.java

public static String toJson(Object javaObject) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
    return mapper.writeValueAsString(javaObject);
}

From source file:com.basistech.rosette.examples.ExampleBase.java

/**
 * Converts a response to JSON string//  w w w . j  a  va2s  . co m
 *
 * @param response {@link com.basistech.rosette.apimodel.Response Response} from RosetteAPI
 * @return the json string.
 * @throws JsonProcessingException if the Jackson library throws an error serializing.
 */
protected static String responseToJson(Response response) throws JsonProcessingException {
    ObjectMapper mapper = ApiModelMixinModule.setupObjectMapper(new ObjectMapper());
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    return mapper.writeValueAsString(response);
}

From source file:com.gtcgroup.test.restful.helper.JprRequestUtilHelper.java

/**
 * @param requestContext/*w ww . ja v  a 2 s . co m*/
 */
public static void filterIncomingJsonRequest(final ClientRequestContext requestContext) {

    final String methodName = "filterIncomingRequest";

    final StringBuilder message = new StringBuilder();
    message.append("JAX-RS ");
    message.append(requestContext.getMethod());
    message.append(": ");
    message.append(requestContext.getUri().toString());

    if (null != requestContext.getEntity()) {

        message.append("\n");
        final ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);

        try {
            message.append(
                    mapper.writerWithDefaultPrettyPrinter().writeValueAsString(requestContext.getEntity()));

        } catch (final Exception e) {
            throw new TestingException("Unable to log incoming request.", e);
        }
    }

    JpcLoggingCacheHelper.getLogger().logModeLifecycle(JprRequestUtilHelper.CLASS_NAME, methodName,
            message.toString());

    return;
}

From source file:parser.JsonWriter.java

/**
 * Creates json file for the cloudDSFPlus with all new attributes.
 * /*from   ww w.  j a  v a 2  s .c  om*/
 * @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.gtcgroup.jped.rest.helper.JprRequestUtilHelper.java

/**
 * @param requestContext/*from ww w.j  a va2  s  .  c  o  m*/
 */
public static void filterIncomingJsonRequest(final ClientRequestContext requestContext) {

    final String methodName = "filterIncomingRequest";

    final StringBuilder message = new StringBuilder();
    message.append("JAX-RS ");
    message.append(requestContext.getMethod());
    message.append(": ");
    message.append(requestContext.getUri().toString());

    if (null != requestContext.getEntity()) {

        message.append("\n");
        final ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);

        try {
            message.append(
                    mapper.writerWithDefaultPrettyPrinter().writeValueAsString(requestContext.getEntity()));

        } catch (final Exception e) {
            throw new JprConvertException(
                    new JpcBasicExceptionPO().setClassName(JprRequestUtilHelper.CLASS_NAME)
                            .setMessage("Unable to log incoming request."),
                    e);
        }
    }

    JpcLoggingCacheHelper.getLogger().logModeLifecycle(JprRequestUtilHelper.CLASS_NAME, methodName,
            message.toString());

    return;
}

From source file:org.apache.drill.common.logical.JSONOptions.java

private static synchronized ObjectMapper getMapper() {
    if (MAPPER == null) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        mapper.configure(Feature.ALLOW_COMMENTS, true);
        MAPPER = mapper;/*ww w .j  a v a  2  s  . c o m*/
    }
    return MAPPER;
}

From source file:org.openmhealth.schema.configuration.JacksonConfiguration.java

public static ObjectMapper newObjectMapper() {

    ObjectMapper objectMapper = new ObjectMapper();

    // we represent JSON numbers as Java BigDecimals
    objectMapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);

    // we serialize dates, date times, and times as strings, not numbers
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    // we preserve time zone offsets when deserializing
    objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);

    // we default to the ISO8601 format for JSR-310 and support Optional
    objectMapper.registerModule(new JavaTimeModule());
    objectMapper.registerModule(new Jdk8Module());

    // but we have to explicitly support the RFC3339 format over ISO8601 to make JSON Schema happy, specifically to
    // prevent the truncation of zero second fields
    SimpleModule rfc3339Module = new SimpleModule("rfc3339Module");
    rfc3339Module.addSerializer(new Rfc3339OffsetDateTimeSerializer(OffsetDateTime.class));
    objectMapper.registerModule(rfc3339Module);

    return objectMapper;
}

From source file:org.mstc.zmq.json.Encoder.java

public static String encode(Object o) throws IOException {
    StringWriter writer = new StringWriter();
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
    JsonFactory factory = mapper.getFactory();
    try (JsonGenerator g = factory.createGenerator(writer)) {
        g.writeStartObject();//from  w  ww . j av a  2s . c  o  m
        for (Field f : o.getClass().getDeclaredFields()) {
            try {
                f.setAccessible(true);
                Object value = f.get(o);
                if (value != null) {
                    if (f.getType().isAssignableFrom(List.class)) {
                        String items = mapper.writeValueAsString(value);
                        g.writeStringField(f.getName(), items);
                    } else if (f.getType().isArray()) {
                        if (f.getType().getComponentType().isAssignableFrom(byte.class)) {
                            g.writeBinaryField(f.getName(), (byte[]) value);
                        } else {
                            int length = Array.getLength(value);
                            g.writeFieldName(f.getName());
                            g.writeStartArray();
                            for (int i = 0; i < length; i++) {
                                Object av = Array.get(value, i);
                                if (av instanceof Double) {
                                    g.writeNumber(new BigDecimal((Double) av).toPlainString());
                                } else if (av instanceof Float) {
                                    g.writeNumber(new BigDecimal((Float) av).toPlainString());
                                } else if (av instanceof Integer) {
                                    g.writeNumber(new BigDecimal((Integer) av).toPlainString());
                                } else {
                                    g.writeObject(av);
                                }
                                /*if (av instanceof Double)
                                g.writeNumber(new BigDecimal((Double) av));
                                else if (av instanceof Float)
                                g.writeNumber(new BigDecimal((Float) av));
                                else if (av instanceof Integer)
                                g.writeNumber((Integer) av);*/
                            }
                            g.writeEndArray();
                        }
                    } else {
                        g.writeObjectField(f.getName(), value);
                    }
                }

            } catch (IllegalAccessException e) {
                logger.warn("Could not get field: {}", f.getName(), e);
            }
        }
        g.writeEndObject();
    }
    if (logger.isDebugEnabled())
        logger.debug(writer.toString());
    return writer.toString();
}

From source file:parser.JsonWriter.java

/**
 * Generates json file for the CloudDSF avoiding any unnecessary attribute serialization.
 * //  w  ww  .  j ava  2  s  .  com
 * @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);
}