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:com.esri.geoportal.harvester.rest.TaskController.java

/**
 * Gets task by id./*from   w w  w. j  a  v a  2s.com*/
 *
 * @param taskId task id
 * @return task info or <code>null</code> if no task found
 */
@RequestMapping(value = "/rest/harvester/tasks/{taskId}/export", method = RequestMethod.GET)
public ResponseEntity<String> export(@PathVariable UUID taskId) {
    try {
        LOG.debug(formatForLog("GET /rest/harvester/tasks/%s", taskId));
        TaskDefinition taskDefinition = engine.getTasksService().readTaskDefinition(taskId);
        if (taskDefinition == null) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Content-disposition", String.format("attachment; filename=\"%s.json\"", taskId));
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        ResponseEntity<String> responseEntity = new ResponseEntity<>(mapper.writeValueAsString(taskDefinition),
                headers, HttpStatus.OK);
        return responseEntity;
    } catch (DataProcessorException | JsonProcessingException ex) {
        LOG.error(formatForLog("Error getting task: %s", taskId), ex);
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.bonitasoft.web.designer.config.DesignerConfig.java

@Bean
public ObjectMapper objectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    //By default all properties without explicit view definition are included in serialization.
    //To use JsonView we have to change this parameter
    objectMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);

    //We don't have to serialize null values
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    objectMapper.registerModule(new JodaModule());
    objectMapper.registerSubtypes(jacksonSubTypes());

    //add Handler to migrate old json
    objectMapper.addHandler(new JacksonDeserializationProblemHandler());

    return objectMapper;
}

From source file:com.corundumstudio.socketio.protocol.JacksonJsonSupport.java

protected void init(ObjectMapper objectMapper) {
    SimpleModule module = new SimpleModule();
    module.setSerializerModifier(modifier);
    module.addDeserializer(Event.class, eventDeserializer);
    module.addDeserializer(AckArgs.class, ackArgsDeserializer);
    objectMapper.registerModule(module);

    objectMapper.setSerializationInclusion(Include.NON_NULL);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN, true);
    objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
}

From source file:com.ikanow.aleph2.data_model.utils.TestBeanTemplateUtils.java

@Test
public void testNumberDeserializer() {
    TestDeserializeBean bean1 = BeanTemplateUtils
            .from("{\"testMap\":{\"test\":1.0}}", TestDeserializeBean.class).get();
    JsonNode jn1 = BeanTemplateUtils.toJson(bean1);

    assertEquals("{\"testMap\":{\"test\":1}}", jn1.toString());

    TestDeserializeBean bean2 = BeanTemplateUtils.from(
            "{\"testMap\":{\"test\":10000000000000,\"test1\":10000000000000.1,\"test2\":\"some string\"}}",
            TestDeserializeBean.class).get();
    JsonNode jn2 = BeanTemplateUtils.toJson(bean2);

    assertEquals(//from w  ww  .j  av  a2s  .co  m
            "{\"testMap\":{\"test\":10000000000000,\"test1\":1.00000000000001E13,\"test2\":\"some string\"}}",
            jn2.toString());

    TestDeserializeBean bean3 = BeanTemplateUtils
            .from("{\"testMap\":{\"test\":1e7, \"test2\":1.0000000000000E7,\"test3\":1E19}}",
                    TestDeserializeBean.class)
            .get();
    JsonNode jn3 = BeanTemplateUtils.toJson(bean3);

    assertEquals("{\"testMap\":{\"test\":10000000,\"test2\":1.0E7,\"test3\":1.0E19}}", jn3.toString());

    //Mapper without the Number deserializer to make sure the double values are staying the same
    ObjectMapper plainMapper = new ObjectMapper();
    plainMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    plainMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    plainMapper.setSerializationInclusion(Include.NON_NULL);

    //Checking that the deserializer doesn't break existing double values
    TestDeserializeBean bean4 = BeanTemplateUtils.from(
            "{\"testMap\":{\"test\":1e7, \"test2\":1.0000000000000E7,\"test3\":1.1,\"test4\":10000000000000.1,\"test4\":6e9,\"test5\":6e300,\"test5\":1E7 }}",
            TestDeserializeBean.class).get();
    JsonNode number_deserialized = BeanTemplateUtils.toJson(bean4);
    JsonNode plain = plainMapper.valueToTree(bean4);

    assertEquals(plain.toString(), number_deserialized.toString());

    // Just check it doesn't mess up actual double deserialization:

    TestDeserializeBean2 bean2_1 = BeanTemplateUtils
            .from("{\"testMap\":{\"test\":1.0}}", TestDeserializeBean2.class).get();
    JsonNode jn2_1 = BeanTemplateUtils.toJson(bean2_1);

    assertEquals("{\"testMap\":{\"test\":1.0}}", jn2_1.toString());

}

From source file:com.acentera.utils.ProjectsHelpers.java

public static String getProjectProvidersAsJson(ProjectProviders prov) {

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    ObjectWriter ow = mapper.writer();//  w  w  w  .jav  a 2s .  co  m
    JSONObject jso = new JSONObject();
    try {
        Logger.debug("PROVIDER IS : " + prov.getId());
        jso.put("provider", ow.writeValueAsString(prov));
        return jso.toString();
    } catch (JsonProcessingException e) {
        e.printStackTrace();
        return null;
    }

}

From source file:org.opendaylight.ovsdb.plugin.ConnectionService.java

private Node handleNewConnection(String identifier, Channel channel, ConnectionService instance)
        throws InterruptedException, ExecutionException {
    Connection connection = new Connection(identifier, channel);
    Node node = connection.getNode();

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.setSerializationInclusion(Include.NON_NULL);

    JsonRpcEndpoint factory = new JsonRpcEndpoint(objectMapper, channel);
    JsonRpcServiceBinderHandler binderHandler = new JsonRpcServiceBinderHandler(factory);
    binderHandler.setNode(node);//  w  w  w .j a va2  s. co m
    channel.pipeline().addLast(binderHandler);

    OvsdbRPC ovsdb = factory.getClient(node, OvsdbRPC.class);
    connection.setRpc(ovsdb);
    ovsdb.registerCallback(instance);
    ovsdbConnections.put(identifier, connection);

    ChannelConnectionHandler handler = new ChannelConnectionHandler();
    handler.setNode(node);
    handler.setConnectionService(this);
    ChannelFuture closeFuture = channel.closeFuture();
    closeFuture.addListener(handler);
    // Keeping the Initial inventory update(s) on its own thread.
    new Thread() {
        Connection connection;
        String identifier;

        @Override
        public void run() {
            try {
                initializeInventoryForNewNode(connection);
            } catch (InterruptedException | ExecutionException e) {
                logger.error("Failed to initialize inventory for node with identifier " + identifier, e);
                ovsdbConnections.remove(identifier);
            }
        }

        public Thread initializeConnectionParams(String identifier, Connection connection) {
            this.identifier = identifier;
            this.connection = connection;
            return this;
        }
    }.initializeConnectionParams(identifier, connection).start();
    return node;
}

From source file:com.wealdtech.jackson.ObjectMapperFactory.java

/**
 * Build an objectmapper from a given configuration.
 *
 * @param configuration/*from   ww w  .ja  v  a  2  s .c om*/
 *          the objectmapper configuration
 * @return an objectmapper
 */
public ObjectMapper build(final ObjectMapperConfiguration configuration) {
    final ObjectMapper mapper = new ObjectMapper(configuration.getFactory().orNull());
    for (Module module : configuration.getModules()) {
        mapper.registerModule(module);
    }
    for (Map.Entry<JsonParser.Feature, Boolean> entry : configuration.getParserFeatures().entrySet()) {
        mapper.getFactory().configure(entry.getKey(), entry.getValue());
    }
    mapper.setInjectableValues(configuration.getInjectableValues());
    if (configuration.getPropertyNamingStrategy().isPresent()) {
        mapper.setPropertyNamingStrategy(configuration.getPropertyNamingStrategy().get());
    }
    if (configuration.getSerializationInclusion().isPresent()) {
        mapper.setSerializationInclusion(configuration.getSerializationInclusion().get());
    }

    return mapper;
}

From source file:org.apache.taverna.robundle.manifest.Manifest.java

/**
 * Write as an RO Bundle JSON-LD manifest
 * /*from  www .j  a  v  a  2s .c om*/
 * @return The path of the written manifest (e.g. ".ro/manifest.json")
 * @throws IOException
 */
public Path writeAsJsonLD() throws IOException {
    Path jsonld = bundle.getFileSystem().getPath(RO, MANIFEST_JSON);
    createDirectories(jsonld.getParent());
    // Files.createFile(jsonld);
    if (!getManifest().contains(jsonld))
        getManifest().add(0, jsonld);
    ObjectMapper om = new ObjectMapper();
    om.addMixInAnnotations(Path.class, PathMixin.class);
    om.addMixInAnnotations(FileTime.class, FileTimeMixin.class);
    om.enable(INDENT_OUTPUT);
    om.disable(WRITE_EMPTY_JSON_ARRAYS);
    om.disable(FAIL_ON_EMPTY_BEANS);
    om.disable(WRITE_NULL_MAP_VALUES);

    om.setSerializationInclusion(Include.NON_NULL);
    try (Writer w = newBufferedWriter(jsonld, Charset.forName("UTF-8"), WRITE, TRUNCATE_EXISTING, CREATE)) {
        om.writeValue(w, this);
    }
    return jsonld;
}

From source file:org.brutusin.json.impl.JacksonCodec.java

public JacksonCodec(ObjectMapper mapper, JacksonFactoryWrapper schemaFactory) {
    if (mapper == null) {
        mapper = new ObjectMapper();

        mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker()
                .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
                .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE));

        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        SimpleModule testModule = new SimpleModule("json-provider-module",
                new Version(1, 0, 0, null, "org.brutusin", "json-provider"));
        testModule.addSerializer(new JsonNodeSerializer());
        testModule.addDeserializer(JsonNode.class, new JsonNodeDeserializer());
        testModule.addSerializer(new InputStreamSerializer());
        testModule.addDeserializer(InputStream.class, new InputStreamDeserializer());
        testModule.addDeserializer(MetaDataInputStream.class, new InputStreamDeserializer());
        mapper.registerModule(testModule);
    }/*w w w  . j a  v a 2 s  .c o m*/
    if (schemaFactory == null) {
        schemaFactory = new JacksonFactoryWrapper(new HashMap<Class, String>(DEFAULT_FORMAT_MAP));
    }
    this.mapper = mapper;
    this.schemaFactory = schemaFactory;
}

From source file:eu.trentorise.opendata.jackan.CkanClient.java

/**
 * Configures the provided Jackson ObjectMapper for create/update/delete
 * operations of Ckan objects. For reading and generic
 * serialization/deserialization of Ckan objects, use
 * {@link #configureObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) }
 * instead. For future compatibility you will need a different object mapper
 * for each class you want to post to ckan. <b> DO NOT </b> call
 * {@link #configureObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) }
 * on the mapper prior to this call./*from  w ww  .j a va2  s . co m*/
 *
 * @param om
 *            a Jackson object mapper
 * @param clazz
 *            the class of the objects you wish to create/update/delete.
 * @since 0.4.1
 */
public static void configureObjectMapperForPosting(ObjectMapper om, Class clazz) {
    configureObjectMapper(om);
    om.setSerializationInclusion(Include.NON_NULL);
    om.addMixInAnnotations(CkanResource.class, CkanResourceForPosting.class);
    om.addMixInAnnotations(CkanDataset.class, CkanDatasetForPosting.class);
    om.addMixInAnnotations(CkanOrganization.class, CkanGroupOrgForPosting.class);
    if (CkanDatasetBase.class.isAssignableFrom(clazz)) {
        // little fix for
        // https://github.com/opendatatrentino/jackan/issues/19
        om.addMixInAnnotations(CkanGroup.class, GroupForDatasetPosting.class);
    } else {
        om.addMixInAnnotations(CkanGroup.class, CkanGroupOrgForPosting.class);
    }

    om.addMixInAnnotations(CkanUser.class, CkanUserForPosting.class);
    om.addMixInAnnotations(CkanTag.class, CkanTagForPosting.class);
}