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:br.com.mv.modulo.model.JSON.java

@Transient
public default String toJSON() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    mapper.setSerializationInclusion(Include.NON_NULL);
    String json = "";
    try {/*  w w w .j av a2  s  . c o m*/
        json = mapper.writeValueAsString(this);
    } catch (JsonProcessingException e) {
        json = "{ error : Error: it's not possible processing JSON }";
        LoggerFactory.getLogger(JSON.class).error("Error: it's not possible processing JSON", e);
    }
    return json;
}

From source file:com.esri.geoportal.commons.ags.client.AgsClient.java

/**
 * Generates token./*from w w  w.  j  av a  2s  . c om*/
 *
 * @param minutes expiration in minutes.
 * @param credentials credentials.
 * @return token response
 * @throws URISyntaxException if invalid URL
 * @throws IOException if accessing token fails
 */
public TokenResponse generateToken(int minutes, SimpleCredentials credentials)
        throws URISyntaxException, IOException {
    HttpPost post = new HttpPost(rootUrl.toURI().resolve("tokens/generateToken"));
    HashMap<String, String> params = new HashMap<>();
    params.put("f", "json");
    if (credentials != null) {
        params.put("username", StringUtils.trimToEmpty(credentials.getUserName()));
        params.put("password", StringUtils.trimToEmpty(credentials.getPassword()));
    }
    params.put("client", "ip");
    params.put("ip", InetAddress.getLocalHost().getHostAddress());
    params.put("expiration", Integer.toString(minutes));
    HttpEntity entity = new UrlEncodedFormEntity(params.entrySet().stream()
            .map(e -> new BasicNameValuePair(e.getKey(), e.getValue())).collect(Collectors.toList()));
    post.setEntity(entity);

    try (CloseableHttpResponse httpResponse = httpClient.execute(post);
            InputStream contentStream = httpResponse.getEntity().getContent();) {
        if (httpResponse.getStatusLine().getStatusCode() >= 400) {
            throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase());
        }
        String responseContent = IOUtils.toString(contentStream, "UTF-8");
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return mapper.readValue(responseContent, TokenResponse.class);
    }
}

From source file:net.solarnetwork.node.dao.jdbc.test.JdbcSettingsDaoTests.java

@Before
public void setup() {
    DatabaseSetup setup = new DatabaseSetup();
    setup.setDataSource(dataSource);/* w ww.  ja v  a2s.  c  o m*/
    setup.init();

    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_NULL);

    dao = new JdbcSettingDao();
    dao.setDataSource(dataSource);
    dao.setTransactionTemplate(new TransactionTemplate(txManager));

    eventAdminMock = EasyMock.createMock(EventAdmin.class);
    dao.setEventAdmin(new StaticOptionalService<EventAdmin>(eventAdminMock));
    settingDao = dao;
}

From source file:com.wadpam.guja.jackson.NonNullObjectMapperProvider.java

@Override
void configureMapper(ObjectMapper mapper) {

    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    // Ignore unknown fields during deserialization
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    // Do not serialize null values
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    // Ignore setterless properties
    mapper.configure(MapperFeature.USE_GETTERS_AS_SETTERS, false);

}

From source file:com.example.restexpmongomvn.controller.VehicleControllerTest.java

/**
 * Test of create method, of class VehicleController.
 *
 * @throws java.io.IOException//w w  w  . j  a v a 2s .c o m
 */
@Test
public void testCreate() throws IOException {
    System.out.println("create");

    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);
    //        System.out.println(testVehicleString);

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

    //        System.out.println(postEntity.getContentType());
    //        System.out.println(postEntity.getContentLength());
    //        System.out.println(EntityUtils.toString(postEntity));
    //        System.out.println(EntityUtils.toByteArray(postEntity).length);
    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);
    assertEquals(parseMongoId(responseString), true);
}

From source file:org.mycontroller.standalone.api.jaxrs.mixins.McJacksonJson2Provider.java

@Override
public void writeTo(Object value, Class<?> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
        throws IOException {
    ObjectMapper mapper = locateMapper(type, mediaType);
    mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // this creates a 'configured' mapper
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    //AddMixIns/*  w  w  w  .  j av  a 2  s  .  co m*/
    mapper.addMixIn(RuleDefinitionTable.class, RuleDefinitionMixin.class);
    mapper.addMixIn(Dashboard.class, DashboardMixin.class);
    mapper.addMixIn(ExternalServerTable.class, ExternalServerMixin.class);
    mapper.addMixIn(Firmware.class, FirmwareMixin.class);
    mapper.addMixIn(ForwardPayload.class, ForwardPayloadMixin.class);
    mapper.addMixIn(GatewayTable.class, GatewayMixin.class);
    mapper.addMixIn(Node.class, NodeMixin.class);
    mapper.addMixIn(OperationTable.class, OperationMixin.class);
    mapper.addMixIn(Resource.class, ResourceMixin.class);
    mapper.addMixIn(ResourcesGroup.class, ResourcesGroupMixin.class);
    mapper.addMixIn(ResourcesGroupMap.class, ResourcesGroupMapMixin.class);
    mapper.addMixIn(ResourcesLogs.class, ResourcesLogsMixin.class);
    mapper.addMixIn(Role.class, RoleMixin.class);
    mapper.addMixIn(Sensor.class, SensorMixin.class);
    mapper.addMixIn(Timer.class, TimerMixin.class);
    mapper.addMixIn(User.class, UserMixin.class);
    mapper.addMixIn(McScript.class, McScriptMixin.class);
    mapper.addMixIn(SensorVariable.class, SensorVariableMixin.class);
    mapper.addMixIn(SensorVariableJson.class, SensorVariableJsonMixin.class);

    if (_logger.isDebugEnabled()) {
        _logger.debug("Response: Headers:{}", httpHeaders);
        _logger.debug("Response: Value:{}", value);
        _logger.debug("Request headers:{}", headers.getRequestHeaders());
    }

    super.writeTo(value, type, genericType, annotations, mediaType, httpHeaders, entityStream);
}

From source file:com.wadpam.guja.jackson.NonEmptyObjectMapperProvider.java

@Override
void configureMapper(ObjectMapper mapper) {

    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    // Ignore unknown fields during deserialization
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    // Do not serialize null values and empty values
    mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    // Ignore setterless properties
    mapper.configure(MapperFeature.USE_GETTERS_AS_SETTERS, false);
}

From source file:org.killbill.billing.plugin.util.http.HttpClient.java

protected ObjectMapper createObjectMapper() {
    final ObjectMapper mapper = new ObjectMapper();

    // Tells the serializer to only include those parameters that are not null
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    // Allow special characters
    mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);

    // Write dates using a ISO-8601 compliant notation
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

    return mapper;
}

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

@Test
public void testJsonIgnore() throws IOException {

    SimulationResponse resp = new SimulationResponse();

    resp.setCapitalGoalProbabilities(Arrays.asList(new Double(10), null, new Double(33)));

    StringWriter sr = new StringWriter();
    ObjectMapper om = new ObjectMapper();

    SimpleModule module = new SimpleModule();
    //      module.addSerializer(List<Double[]>.class, new ListOfDoubleArraySerializer());
    module.addSerializer(Double[].class, new MyDoubleArraySerializer());
    om.registerModule(module);//www  .  j a v a 2 s  . c  o  m
    om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    om.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

    om.writeValue(sr, resp);

    System.out.println("SimulationResponse=" + sr);

}

From source file:org.commonjava.cartographer.result.ProjectPathsResultTest.java

@Test
public void jsonRoundTrip() throws Exception {
    ProjectPathsResult in = new ProjectPathsResult();
    ProjectVersionRef ref = new SimpleProjectVersionRef("org.foo", "bar", "1");
    in.addPath(ref,//www  . j a  va 2  s .  co  m
            new ProjectPath(
                    Collections.singletonList(new SimpleParentRelationship(URI.create("http://nowhere.com"),
                            ref, new SimpleProjectVersionRef("org.dep", "project", "1.1")))));

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModules(new ProjectVersionRefSerializerModule(), new ProjectRelationshipSerializerModule());
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

    String json = mapper.writeValueAsString(in);

    Logger logger = LoggerFactory.getLogger(getClass());
    logger.debug(json);

    ProjectPathsResult out = mapper.readValue(json, ProjectPathsResult.class);
}