下面列出了com.fasterxml.jackson.databind.ObjectMapper#setSerializationInclusion ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
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 );
}
@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;
}
/**
* 泛型方法实现
* @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);
}
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objMapper = new ObjectMapper();
objMapper.enable(SerializationFeature.INDENT_OUTPUT);
objMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return objMapper;
}
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();
}
/**
* 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);
}
/**
* 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);
}
/**
* 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;
}
@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;
}
/**
* 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();
}
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;
}
@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());
}
}
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;
}
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;
}
private static ObjectMapper setupObjectMapper(final ObjectMapper objectMapper) {
objectMapper.setSerializationInclusion(Include.NON_NULL);
objectMapper.registerModule(new Jdk8Module());
return objectMapper;
}
private String convertObjectToJson(Object request) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
return mapper.writeValueAsString(request);
}
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;
}
/**
* 字符串转换为 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);
}
/**
* 字符串转换为 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);
}