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

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

Introduction

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

Prototype

public ObjectMapper setSerializationInclusion(JsonInclude.Include incl) 

Source Link

Document

Method for setting defalt POJO property inclusion strategy for serialization.

Usage

From source file:parser.JsonWriter.java

/**
 * Generates json file for the CloudDSF avoiding any unnecessary attribute serialization.
 * //  www  . j a v a  2s. 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:com.vmware.bdd.cli.commands.CommandsUtils.java

public static void prettyJsonOutput(Object object, String fileName) throws Exception {
    OutputStream out = null;//from  w ww. j a va  2  s.  co  m
    try {
        if (fileName != null) {
            out = new FileOutputStream(fileName);
        } else {
            out = System.out;
        }
        JsonFactory factory = new JsonFactory();
        JsonGenerator generator = factory.createJsonGenerator(out);
        ObjectMapper mapper = getMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        generator.setCodec(mapper);
        DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
        DefaultPrettyPrinter.Indenter indenter = new DefaultPrettyPrinter.Lf2SpacesIndenter();
        prettyPrinter.indentArraysWith(indenter);
        generator.setPrettyPrinter(prettyPrinter);
        generator.writeObject(object);
        writeEndingMsgToScreen(fileName);
    } finally {
        if (out != null && !(out instanceof PrintStream)) {
            out.close();
        }
    }
}

From source file:com.hybridbpm.core.util.HybridbpmCoreUtil.java

public static <T> T jsonToObject(String json, Class<T> clazz) {
    try {/*from w ww. ja v  a  2 s .c o  m*/
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return objectMapper.readValue(json, clazz);
    } catch (Exception ex) {
        logger.log(Level.SEVERE, ex.getMessage(), ex);
        throw new RuntimeException(ex);
    }
}

From source file:com.hybridbpm.core.util.HybridbpmCoreUtil.java

public static Object jsonByteArrayObject(byte[] json, Class clazz) {
    try {//from   w  w  w  . j a  va 2s  . c  o  m
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return objectMapper.readValue(json, clazz);
    } catch (Exception ex) {
        logger.log(Level.SEVERE, ex.getMessage(), ex);
        throw new RuntimeException(ex);
    }
}

From source file:com.hybridbpm.core.util.HybridbpmCoreUtil.java

private static byte[] objectToJsonByteArray(Object object) {
    try {//from ww  w .j  a  v  a 2s.  co m
        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:com.ikanow.aleph2.data_model.utils.BeanTemplateUtils.java

/** Configures a mapper with the desired properties for use in Aleph2
 * @param configure_me - leave this empty to create a new mapper, or add one to configure an existing mapper
 * @return//w ww . j a  va  2s.  c om
 */
public static ObjectMapper configureMapper(final Optional<ObjectMapper> configure_me) {
    final ObjectMapper mapper = configure_me.orElse(new ObjectMapper());
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE);

    final SimpleModule module = new SimpleModule();
    module.addDeserializer(Number.class, new NumberDeserializer());
    mapper.registerModule(module);

    return mapper;
}

From source file:de.fau.cs.inf2.tree.evaluation.TreeEvalIO.java

public static ObjectMapper createJSONMapper(final DataFormat format) {
    final ObjectMapper mapper;
    {/*from   ww  w .  j av a  2 s  .  com*/
        switch (format) {
        case FORMAT_JSON: {
            mapper = new ObjectMapper();
            break;
        }
        default: {
            assert (false);
            return null;
        }
        }
    }

    // configure mapper
    {
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.setVisibilityChecker(mapper.getVisibilityChecker().with(JsonAutoDetect.Visibility.NONE));
        mapper.setSerializationInclusion(Include.NON_NULL);
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S");
        mapper.setDateFormat(df);
        addMixIns(mapper, TimeSummary.class, MixInTimeSummary.class);
        addMixIns(mapper, DiffSummary.class, MixInDiffSummary.class);
        addMixIns(mapper, TreeMatcherTypeEnum.class, MixInTreeMatcherTypeEnum.class);
        addMixIns(mapper, PsoResult.class, MixInPSOResult.class);
        addMixIns(mapper, ValidationDecision.class, MixInValidationDecision.class);
        addMixIns(mapper, ValidationDecisionList.class, MixInValidationDecisionList.class);
        addMixIns(mapper, ValidationEntry.class, MixInValidationEntry.class);
        addMixIns(mapper, ValidationEnum.class, MixInValidationEnum.class);
        addMixIns(mapper, ValidationRating.class, MixInValidationRating.class);
        addMixIns(mapper, ValidationInputSummary.class, MixInValidationInputSummary.class);
        addMixIns(mapper, ValidationInfo.class, MixInValidationInfo.class);

    }

    return mapper;
}

From source file:com.addthis.codec.jackson.Jackson.java

public static ObjectMapper toggleObjectMapperOptions(ObjectMapper objectMapper) {
    // potentially useful features, but disabled by default to maintain existing behavior

    // ignore final fields
    objectMapper.disable(ALLOW_FINAL_FIELDS_AS_MUTATORS);
    // do not try to modify existing containers
    objectMapper.disable(USE_GETTERS_AS_SETTERS);
    // public getters do not automaticaly imply codec should try to write to it
    objectMapper.disable(INFER_PROPERTY_MUTATORS);

    // more aggressive failure detection
    objectMapper.enable(FAIL_ON_READING_DUP_TREE_KEY);

    // essentially auto-collection everywhere, but that seems fine and this is easy
    objectMapper.enable(ACCEPT_SINGLE_VALUE_AS_ARRAY);

    // don't write out null fields
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    return objectMapper;
}

From source file:com.athina.queue.manager.JobQueueManagerApplication.java

@Bean
public MappingJackson2HttpMessageConverter jacksonConverter() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.registerModule(new JSR310Module());
    return new MappingJackson2HttpMessageConverter(mapper);
}

From source file:io.github.autsia.crowly.tests.IntegrationTestingUtils.java

public byte[] convertObjectToJsonBytes(Object object) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    return mapper.writeValueAsBytes(object);
}