Java Code Examples for com.fasterxml.jackson.databind.ObjectMapper#setSerializationInclusion()

The following examples show how to use com.fasterxml.jackson.databind.ObjectMapper#setSerializationInclusion() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JacksonConfig.java    From xmall with MIT License 7 votes vote down vote up
@Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();

        // 通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化
        // Include.Include.ALWAYS 默认
        // Include.NON_DEFAULT 属性为默认值不序列化
        // Include.NON_EMPTY 属性为 空("") 或者为 NULL 都不序列化,则返回的json是没有这个字段的。这样对移动端会更省流量
        // Include.NON_NULL 属性为NULL 不序列化,就是为null的字段不参加序列化
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        // 字段保留,将null值转为""
//        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>()
//        {
//            @Override
//            public void serialize(Object o, JsonGenerator jsonGenerator,
//                                  SerializerProvider serializerProvider)
//                    throws IOException, JsonProcessingException
//            {
//                jsonGenerator.writeString("");
//            }
//        });
        return objectMapper;
    }
 
Example 2
Source File: HeroicMappers.java    From heroic with Apache License 2.0 6 votes vote down vote up
public static ObjectMapper json(final QueryParser parser) {
    final ObjectMapper mapper = new ObjectMapper();

    mapper.addMixIn(AggregationInstance.class, TypeNameMixin.class);
    mapper.addMixIn(Aggregation.class, TypeNameMixin.class);

    mapper.registerModule(new Jdk8Module().configureAbsentsAsNulls(true));
    mapper.registerModule(commonSerializers());
    mapper.registerModule(jsonSerializers());
    mapper.registerModule(new KotlinModule());

    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    mapper.registerModule(FilterRegistry.registry().module(parser));

    return mapper;
}
 
Example 3
Source File: TestUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static byte[] convertObjectToJsonBytes( Object object ) throws IOException
{
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion( JsonInclude.Include.NON_NULL );
    objectMapper.configure( SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false );
    objectMapper.configure( SerializationFeature.FAIL_ON_EMPTY_BEANS, false );
    objectMapper.configure( SerializationFeature.WRAP_EXCEPTIONS, true );
    objectMapper.setSerializationInclusion( JsonInclude.Include.NON_NULL );

    objectMapper.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false );
    objectMapper.configure( DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, true );
    objectMapper.configure( DeserializationFeature.WRAP_EXCEPTIONS, true );

    objectMapper.disable( MapperFeature.AUTO_DETECT_FIELDS );
    objectMapper.disable( MapperFeature.AUTO_DETECT_CREATORS );
    objectMapper.disable( MapperFeature.AUTO_DETECT_GETTERS );
    objectMapper.disable( MapperFeature.AUTO_DETECT_SETTERS );
    objectMapper.disable( MapperFeature.AUTO_DETECT_IS_GETTERS );

    return objectMapper.writeValueAsBytes( object );
}
 
Example 4
Source File: SiteToSiteCliMain.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Prints the usage to System.out
 *
 * @param errorMessage optional error message
 * @param options      the options object to print usage for
 */
public static void printUsage(String errorMessage, Options options) {
    if (errorMessage != null) {
        System.out.println(errorMessage);
        System.out.println();
        System.out.println();
    }
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    System.out.println("s2s is a command line tool that can either read a list of DataPackets from stdin to send over site-to-site or write the received DataPackets to stdout");
    System.out.println();
    System.out.println("The s2s cli input/output format is a JSON list of DataPackets.  They can have the following formats:");
    try {
        System.out.println();
        objectMapper.writeValue(System.out, Arrays.asList(new DataPacketDto("hello nifi".getBytes(StandardCharsets.UTF_8)).putAttribute("key", "value")));
        System.out.println();
        System.out.println("Where data is the base64 encoded value of the FlowFile content (always used for received data) or");
        System.out.println();
        objectMapper.writeValue(System.out, Arrays.asList(new DataPacketDto(new HashMap<>(), new File("EXAMPLE").getAbsolutePath()).putAttribute("key", "value")));
        System.out.println();
        System.out.println("Where dataFile is a file to read the FlowFile content from");
        System.out.println();
        System.out.println();
        System.out.println("Example usage to send a FlowFile with the contents of \"hey nifi\" to a local unsecured NiFi over http with an input port named input:");
        System.out.print("echo '");
        DataPacketDto dataPacketDto = new DataPacketDto("hey nifi".getBytes(StandardCharsets.UTF_8));
        dataPacketDto.setAttributes(null);
        objectMapper.writeValue(System.out, Arrays.asList(dataPacketDto));
        System.out.println("' | bin/s2s.sh -n input -p http");
        System.out.println();
    } catch (IOException e) {
        e.printStackTrace();
    }
    HelpFormatter helpFormatter = new HelpFormatter();
    helpFormatter.setWidth(160);
    helpFormatter.printHelp("s2s", options);
    System.out.flush();
}
 
Example 5
Source File: ConfigurationDataUtils.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public static ObjectMapper create() {
    ObjectMapper mapper = new ObjectMapper();
    // forward compatibility for the properties may go away in the future
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
    mapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, false);
    mapper.setSerializationInclusion(Include.NON_NULL);
    return mapper;
}
 
Example 6
Source File: ParserUtils.java    From QVisual with Apache License 2.0 5 votes vote down vote up
public static ObjectMapper getMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.disable(FAIL_ON_UNKNOWN_PROPERTIES);
    mapper.disable(FAIL_ON_EMPTY_BEANS);
    mapper.setSerializationInclusion(NON_NULL);

    return mapper;
}
 
Example 7
Source File: AbstractItTest.java    From yang2swagger with Eclipse Public License 1.0 5 votes vote down vote up
@After
public void printSwagger() throws IOException {
    if(log.isDebugEnabled() && swagger != null) {
        StringWriter writer = new StringWriter();
        ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mapper.writeValue(writer, swagger);
        log.debug(writer.toString());
    }
}
 
Example 8
Source File: JavaUtils.java    From Singularity with Apache License 2.0 5 votes vote down vote up
public static ObjectMapper newObjectMapper() {
  final ObjectMapper mapper = new ObjectMapper();
  mapper.setSerializationInclusion(Include.NON_ABSENT);
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  mapper.registerModule(new GuavaModule());
  mapper.registerModule(new ProtobufModule());
  mapper.registerModule(new Jdk8Module());
  return mapper;
}
 
Example 9
Source File: T212Configurator.java    From hj-t212-parser with Apache License 2.0 5 votes vote down vote up
/**
 * 泛型方法实现
 * @see Configurator#config(Object)
 * @param dataReverseConverter
 */
private void configure(DataReverseConverter dataReverseConverter) {
    ObjectMapper objectMapper = this.objectMapper;
    if(objectMapper == null){
        objectMapper = new ObjectMapper()
                .configure(FAIL_ON_UNKNOWN_PROPERTIES,false);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }
    dataReverseConverter.setObjectMapper(objectMapper);
}
 
Example 10
Source File: JsonHelperJackson2.java    From symbol-sdk-java with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("squid:CallToDeprecatedMethod")
public static ObjectMapper configureMapper(ObjectMapper objectMapper) {
    objectMapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS,
        false); //I cannot annotate the generated classes like the alternative recommended by jackson
    objectMapper.configure(DeserializationFeature.USE_LONG_FOR_INTS, true);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    SimpleModule module = new SimpleModule();
    module.addSerializer(BigInteger.class, new BigIntegerSerializer());
    objectMapper.registerModule(module);
    objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
    objectMapper.setSerializationInclusion(Include.NON_EMPTY);
    objectMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
    objectMapper.registerModule(new Jdk8Module());
    return objectMapper;
}
 
Example 11
Source File: ESStorageEngine.java    From BioSolr with Apache License 2.0 5 votes vote down vote up
/**
 * Get an object mapper for serializing the product data.
 * @return the object mapper.
 */
private ObjectMapper getSerializationMapper() {
	ObjectMapper mapper = new ObjectMapper();
	mapper.setSerializationInclusion(Include.NON_NULL);
	mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
	return mapper;
}
 
Example 12
Source File: TestUtil.java    From cubeai with Apache License 2.0 5 votes vote down vote up
/**
 * Convert an object to JSON byte array.
 *
 * @param object
 *            the object to convert
 * @return the JSON byte array
 * @throws IOException
 */
public static byte[] convertObjectToJsonBytes(Object object)
        throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    JavaTimeModule module = new JavaTimeModule();
    mapper.registerModule(module);

    return mapper.writeValueAsBytes(object);
}
 
Example 13
Source File: ExtendedQALDJSONLoader.java    From NLIWOD with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Writes the json to an byte array
 *
 * @param json
 * @return the given json as byte representation
 * @throws JsonProcessingException
 */
public static byte[] writeJson(final Object json) throws JsonProcessingException {

	ObjectMapper mapper = new ObjectMapper();
	mapper.setSerializationInclusion(Include.NON_NULL);
	mapper.setSerializationInclusion(Include.NON_EMPTY);
	mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);

	return mapper.writer().writeValueAsBytes(json);

}
 
Example 14
Source File: SnsNotificationSender.java    From data-highway with Apache License 2.0 5 votes vote down vote up
public SnsNotificationSender(AmazonSNSAsync sns, TopicArnFactory topicArnFactory, MessageFactory messageFactory) {
  log.info("Starting SNS notifier.");
  this.sns = sns;
  this.topicArnFactory = topicArnFactory;
  this.messageFactory = messageFactory;
  ObjectMapper mapper = new ObjectMapper();
  mapper.setSerializationInclusion(Include.NON_NULL);
  objectWriter = mapper.writer();
}
 
Example 15
Source File: WebConfig.java    From Spring with Apache License 2.0 5 votes vote down vote up
@Bean
public ObjectMapper objectMapper() {
    ObjectMapper objMapper = new ObjectMapper();
    objMapper.enable(SerializationFeature.INDENT_OUTPUT);
    objMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    return objMapper;
}
 
Example 16
Source File: Serializer.java    From orion with Apache License 2.0 4 votes vote down vote up
private static ObjectMapper setupObjectMapper(final ObjectMapper objectMapper) {
  objectMapper.setSerializationInclusion(Include.NON_NULL);
  objectMapper.registerModule(new Jdk8Module());
  return objectMapper;
}
 
Example 17
Source File: UserControllerTest.java    From pivotal-bank-demo with Apache License 2.0 4 votes vote down vote up
private String convertObjectToJson(Object request) throws Exception {
	ObjectMapper mapper = new ObjectMapper();
	mapper.setSerializationInclusion(Include.NON_NULL);
	return mapper.writeValueAsString(request);
}
 
Example 18
Source File: ShoppingCartStateSerDesJacksonImpl.java    From yes-cart with Apache License 2.0 4 votes vote down vote up
public ShoppingCartStateSerDesJacksonImpl(final AmountCalculationStrategy amountCalculationStrategy) {

        mapper = new ObjectMapper();

        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        SimpleModule module = new SimpleModule("cart", new Version(2, 3, 0, null, "org.yes", "core-module-cart"));
        module.addAbstractTypeMapping(Total.class, TotalImpl.class);
        module.addAbstractTypeMapping(MutableShoppingContext.class, ShoppingContextImpl.class);
        module.addAbstractTypeMapping(MutableOrderInfo.class, OrderInfoImpl.class);
        module.addAbstractTypeMapping(CartItem.class, CartItemImpl.class);

        mapper.registerModule(module);

        this.amountCalculationStrategy = amountCalculationStrategy;

    }
 
Example 19
Source File: MapperUtils.java    From MyShopPlus with Apache License 2.0 2 votes vote down vote up
/**
 * 字符串转换为 Map<String, Object>
 *
 * @param jsonString
 * @return
 * @throws Exception
 */
public static <T> Map<String, Object> json2map(String jsonString) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    return mapper.readValue(jsonString, Map.class);
}
 
Example 20
Source File: MapperUtils.java    From yfshop with Apache License 2.0 2 votes vote down vote up
/**
 * 字符串转换为 Map<String, Object>
 *
 * @param jsonString
 * @return
 * @throws Exception
 */
public static <T> Map<String, Object> json2map(String jsonString) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    return mapper.readValue(jsonString, Map.class);
}