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.example.restexpmongomvn.controller.VehicleControllerTest.java

/**
 * Test of read method, of class VehicleController.
 * @throws com.fasterxml.jackson.core.JsonProcessingException
 * @throws java.io.IOException//from   www.  j  av  a  2  s.  c  om
 */
@Test
public void testRead() throws JsonProcessingException, IOException {
    System.out.println("read");

    Vehicle testVehicle = new Vehicle(2015, "Test", "Vehicle", Color.Red, "4-Door Sedan");
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(Include.NON_EMPTY);
    String testVehicleString = objectMapper.writeValueAsString(testVehicle);

    StringEntity postEntity = new StringEntity(testVehicleString,
            ContentType.create("application/json", "UTF-8"));
    postEntity.setChunked(true);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httppost = new HttpPost(BASE_URL + "/restexpress/vehicles");
    httppost.setEntity(postEntity);
    CloseableHttpResponse response = httpclient.execute(httppost);

    String responseString = new BasicResponseHandler().handleResponse(response);
    responseString = responseString.replaceAll("^\"|\"$", "");

    // Get vehicle based on MongoDB id
    HttpGet httpget = new HttpGet(BASE_URL + "/restexpress/vehicle/" + responseString);
    CloseableHttpResponse response2 = httpclient.execute(httpget);

    String responseString2 = new BasicResponseHandler().handleResponse(response2);

    ResponseHandler<Vehicle> rh = new ResponseHandler<Vehicle>() {

        @Override
        public Vehicle handleResponse(final HttpResponse response) throws IOException {
            StatusLine statusLine = response.getStatusLine();
            HttpEntity entity = response.getEntity();
            if (statusLine.getStatusCode() >= 300) {
                throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
            }
            if (entity == null) {
                throw new ClientProtocolException("Response contains no content");
            }
            Gson gson = new GsonBuilder().setPrettyPrinting().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
                    .create();
            ContentType contentType = ContentType.getOrDefault(entity);
            Charset charset = contentType.getCharset();
            Reader reader = new InputStreamReader(entity.getContent(), "UTF-8");

            //                String inputStreamString = new Scanner(entity.getContent(), "UTF-8").useDelimiter("\\A").next();
            //                System.out.println(inputStreamString);

            return gson.fromJson(reader, Vehicle.class);
        }
    };
    Vehicle vehicle = httpclient.execute(httpget, rh);
    System.out.println("b");

    //        MongodbEntityRepository<Vehicle> vehicleRepository;
    //        VehicleController instance = new VehicleController(vehicleRepository);
    //        Vehicle result = instance.read(request, response);
    //        assertEquals(parseMongoId(responseString), true);
}

From source file:com.nike.cerberus.module.CerberusModule.java

/**
 * Object mapper for handling CloudFormation parameters and outputs.
 *
 * @return Object mapper//from ww w .j av a2s .co  m
 */
@Provides
@Singleton
@Named(CF_OBJECT_MAPPER)
public ObjectMapper cloudFormationObjectMapper() {
    final ObjectMapper om = new ObjectMapper();
    om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    om.setSerializationInclusion(JsonInclude.Include.NON_ABSENT);
    return om;
}

From source file:com.netflix.discovery.converters.jackson.EurekaJsonJacksonCodec.java

private ObjectMapper createObjectMapper(KeyFormatter keyFormatter, boolean compact, boolean wrapped) {
    ObjectMapper newMapper = new ObjectMapper();
    SimpleModule jsonModule = new SimpleModule();
    jsonModule.setSerializerModifier(/*from   ww w  . jav a2 s  .  co  m*/
            EurekaJacksonJsonModifiers.createJsonSerializerModifier(keyFormatter, compact));

    newMapper.registerModule(jsonModule);
    newMapper.setSerializationInclusion(Include.NON_NULL);
    newMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, wrapped);
    newMapper.configure(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, false);
    newMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, wrapped);
    newMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    newMapper.addMixIn(Applications.class, ApplicationsJsonMixIn.class);
    if (compact) {
        addMiniConfig(newMapper);
    } else {
        newMapper.addMixIn(InstanceInfo.class, InstanceInfoJsonMixIn.class);
    }
    return newMapper;
}

From source file:com.netflix.conductor.server.JerseyModule.java

@Provides
@Singleton/* w  ww.j  a  va  2s.  c o m*/
public ObjectMapper objectMapper() {
    final ObjectMapper om = new ObjectMapper();
    om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    om.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
    om.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
    om.setSerializationInclusion(Include.NON_NULL);
    om.setSerializationInclusion(Include.NON_EMPTY);
    return om;
}

From source file:ro.nextreports.engine.chart.NextChart.java

public String toJson() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.setSerializationInclusion(Include.NON_EMPTY);
    StringWriter writer = new StringWriter();
    try {/*from  w w  w  . j  a  v  a 2s. c om*/
        mapper.writeValue(writer, this);
        return writer.toString();
    } catch (Exception ex) {
        ex.printStackTrace();
        return "Error : " + ex.getMessage();
    }
}

From source file:org.openwms.TransportationStarter.java

public @Primary @Bean(name = TMSConstants.BEAN_NAME_OBJECTMAPPER) ObjectMapper jackson2ObjectMapper() {
    ObjectMapper om = new ObjectMapper();
    om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    om.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false);
    om.configure(SerializationFeature.INDENT_OUTPUT, true);
    om.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    om.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    return om;//from   w  w w.  ja  v a  2s.  c o  m
}

From source file:org.opencb.cellbase.lib.impl.GeneMongoDBAdaptor.java

@Override
public QueryResult<Gene> get(Query query, QueryOptions options) {
    Bson bson = parseQuery(query);/*from   w  ww .ja  va2s .  c om*/
    options = addPrivateExcludeOptions(options);

    if (postDBFilteringParametersEnabled(query)) {
        QueryResult<Document> nativeQueryResult = postDBFiltering(query, mongoDBCollection.find(bson, options));
        QueryResult<Gene> queryResult = new QueryResult<Gene>(nativeQueryResult.getId(),
                nativeQueryResult.getDbTime(), nativeQueryResult.getNumResults(),
                nativeQueryResult.getNumTotalResults(), nativeQueryResult.getWarningMsg(),
                nativeQueryResult.getErrorMsg(), null);
        ObjectMapper jsonObjectMapper = new ObjectMapper();
        jsonObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        jsonObjectMapper.configure(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS, true);
        ObjectWriter objectWriter = jsonObjectMapper.writer();
        queryResult.setResult(nativeQueryResult.getResult().stream().map(document -> {
            try {
                return this.objectMapper.readValue(objectWriter.writeValueAsString(document), Gene.class);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }).collect(Collectors.toList()));
        return queryResult;
    } else {
        return mongoDBCollection.find(bson, null, Gene.class, options);
    }
}

From source file:com.github.ibm.domino.client.BaseClient.java

protected void init(String pathSuffix) throws RuntimeException {

    if (database == null || database.isEmpty()) {
        throw new RuntimeErrorException(new Error("Database parameter not found"));
    }/*from www  . ja va 2 s. c o m*/
    if (ignoreHostNameMatching) {
        HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
    }

    StringBuilder p = new StringBuilder();
    if (pathSuffix != null && !pathSuffix.isEmpty()) {
        p.append("/mail");
        p.append("/").append(database);
    }
    p.append("/api/calendar");
    if (pathSuffix != null && !pathSuffix.isEmpty()) {
        p.append("/").append(pathSuffix);
    }
    setPath(p.toString());

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.setSerializationInclusion(Include.NON_NULL);
    //        mapper.configure(SerializationFeature. WRITE_NULL_MAP_VALUES, false);

    mapper.registerModule(new Jackson2HalModule());

    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(
            Arrays.asList(MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM));
    converter.setObjectMapper(mapper);

    restTemplate = new RestTemplate(Collections.<HttpMessageConverter<?>>singletonList(converter));

    List<ClientHttpRequestInterceptor> interceptors = Collections
            .<ClientHttpRequestInterceptor>singletonList(new BasicAuthorizationInterceptor(username, password));
    restTemplate.setRequestFactory(
            new InterceptingClientHttpRequestFactory(restTemplate.getRequestFactory(), interceptors));

}

From source file:wercker4j.request.RequestBuilder.java

/**
 * post will call build API to create/*  ww w. j  ava  2 s.  co  m*/
 *
 * @param option option to call trigger new build API
 * @return responseWrapper
 * @throws Wercker4jException fault statusCode and IO error
 */
public ResponseWrapper post(CreateBuildOption option) throws Wercker4jException {
    String url = UriTemplate.fromTemplate(endpoint + "/builds").expand();
    HttpPost httpPost = new HttpPost(url);
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_NULL);
    try {
        httpPost.setEntity(new StringEntity(mapper.writeValueAsString(option), "UTF-8"));
        return callPostAPI(httpPost);
    } catch (Exception e) {
        throw new Wercker4jException(e);
    }
}

From source file:wercker4j.request.RequestBuilder.java

/**
 * post will call token API to create//from  ww w  .  ja  v a  2  s .com
 *
 * @param option option to call trigger new token API
 * @return responseWrapper
 * @throws Wercker4jException fault statusCode and IO error
 */
public ResponseWrapper post(CreateTokenOption option) throws Wercker4jException {
    String url = UriTemplate.fromTemplate(endpoint + "/tokens").expand();
    HttpPost httpPost = new HttpPost(url);
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_NULL);
    try {
        httpPost.setEntity(new StringEntity(mapper.writeValueAsString(option), "UTF-8"));
        return callPostAPI(httpPost);
    } catch (Exception e) {
        throw new Wercker4jException(e);
    }
}