下面列出了怎么用com.fasterxml.jackson.databind.ser.std.ToStringSerializer的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 转换器全局配置
*
* @param converters
* @return
*/
@Bean
public HttpMessageConverters httpMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = new ObjectMapper();
// 忽略为空的字段
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.getSerializationConfig().withFeatures(
SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
/**
* 序列换成json时,将所有的long变成string
* js中long过长精度丢失
*/
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
jackson2HttpMessageConverter.setObjectMapper(objectMapper);
log.info("MappingJackson2HttpMessageConverter [{}]", jackson2HttpMessageConverter);
return new HttpMessageConverters(jackson2HttpMessageConverter);
}
/**
* jackson 配置
*
* @return mapper
*/
private static ObjectMapper createJackson() {
Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder = Jackson2ObjectMapperBuilder.json();
jackson2ObjectMapperBuilder.simpleDateFormat(DatePattern.NORM_DATETIME_PATTERN);
ObjectMapper build = jackson2ObjectMapperBuilder.build();
// 忽略空
build.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// 驼峰转下划线
// build.setPropertyNamingStrategy(new PropertyNamingStrategy.SnakeCaseStrategy());
// long to String
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
build.registerModule(simpleModule);
//
build.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// build.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);
return build;
}
@Bean
public MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = new ObjectMapper();
//设置日期格式
//TODO 需要兼容时间和日期格式
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
//Long 转String类型,否则js丢失精度
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
//支持jdk8新特性
objectMapper
.registerModule(new ParameterNamesModule())
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule())
.registerModule(simpleModule)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
return mappingJackson2HttpMessageConverter;
}
TestModule()
{
addSerializer(Interval.class, ToStringSerializer.instance);
addDeserializer(
Interval.class, new StdDeserializer<Interval>(Interval.class)
{
@Override
public Interval deserialize(
JsonParser jsonParser, DeserializationContext deserializationContext
) throws IOException, JsonProcessingException
{
return new Interval(jsonParser.getText());
}
}
);
}
private static ObjectMapper addCustomModules(ObjectMapper mapper, boolean intern) {
// with this mixin UnconfiguredTargetNode properties are flattened with
// UnconfiguredTargetNodeWithDeps
// properties
// for prettier view. It only works for non-typed serialization.
mapper.addMixIn(
UnconfiguredTargetNodeWithDeps.class,
UnconfiguredTargetNodeWithDeps.UnconfiguredTargetNodeWithDepsUnwrappedMixin.class);
// Serialize and deserialize UnconfiguredBuildTarget as string
SimpleModule buildTargetModule = new SimpleModule("BuildTarget");
buildTargetModule.addSerializer(UnconfiguredBuildTarget.class, new ToStringSerializer());
buildTargetModule.addDeserializer(
UnconfiguredBuildTarget.class,
new FromStringDeserializer<UnconfiguredBuildTarget>(UnconfiguredBuildTarget.class) {
@Override
protected UnconfiguredBuildTarget _deserialize(
String value, DeserializationContext ctxt) {
return UnconfiguredBuildTargetParser.parse(value, intern);
}
});
mapper.registerModule(buildTargetModule);
mapper.registerModule(forwardRelativePathModule());
return mapper;
}
private static SimpleModule forwardRelativePathModule() {
SimpleModule module = new SimpleModule();
module.addSerializer(ForwardRelativePath.class, new ToStringSerializer());
module.addDeserializer(
ForwardRelativePath.class,
new FromStringDeserializer<ForwardRelativePath>(ForwardRelativePath.class) {
@Override
protected ForwardRelativePath _deserialize(String value, DeserializationContext ctxt)
throws IOException {
return ForwardRelativePath.of(value);
}
@Override
protected ForwardRelativePath _deserializeFromEmptyString() throws IOException {
return ForwardRelativePath.EMPTY;
}
});
return module;
}
/**
* BigDecimal 转化为String
* @return
*/
@Bean
public MappingJackson2HttpMessageConverter toStringConverter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(BigDecimal.class, ToStringSerializer.instance);
mapper.registerModule(simpleModule);
converter.setObjectMapper(mapper);
return converter;
}
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
// 排序key
objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
//忽略空bean转json错误
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
//忽略在json字符串中存在,在java类中不存在字段,防止错误。
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
/**
* 序列换成json时,将所有的long变成string
* 因为js中得数字类型不能包含所有的java long值
*/
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
// 兼容fastJson 的一些空值处理
SerializerFeature[] features = new SerializerFeature[]{
WriteNullListAsEmpty,
WriteNullStringAsEmpty,
WriteNullNumberAsZero,
WriteNullBooleanAsFalse,
WriteNullMapAsEmpty
};
objectMapper.setSerializerFactory(objectMapper.getSerializerFactory().withSerializerModifier(new FastJsonSerializerFeatureCompatibleForJackson(features)));
log.info("ObjectMapper [{}]", objectMapper);
return objectMapper;
}
/**
* json 类型参数 序列化问题
* Long -> string
* date -> string
*
* @param builder
* @return
*/
@Bean
@Primary
@ConditionalOnMissingBean
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false)
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.timeZone(TimeZone.getTimeZone("Asia/Shanghai"))
.build();
//忽略未知字段
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//日期格式
SimpleDateFormat outputFormat = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
objectMapper.setDateFormat(outputFormat);
SimpleModule simpleModule = new SimpleModule();
/**
* 将Long,BigInteger序列化的时候,转化为String
*/
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
simpleModule.addSerializer(BigInteger.class, ToStringSerializer.instance);
simpleModule.addSerializer(BigDecimal.class, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
return objectMapper;
}
@Bean
@ConditionalOnMissingBean
public Module customModule() {
SimpleModule module = new SimpleModule();
module.addSerializer(LocalDateTime.class, new LocalDatetimeFormatter.LocalDateTimeSerializer());
module.addDeserializer(LocalDateTime.class, new LocalDatetimeFormatter.LocalDateTimeDeserializer());
module.addSerializer(LocalDate.class, new LocalDateFormatter.LocalDateSerializer());
module.addDeserializer(LocalDate.class, new LocalDateFormatter.LocalDateDeserializer());
module.addSerializer(Long.class, ToStringSerializer.instance);
return module;
}
/**
* json 类型参数 序列化问题
* Long -> string
* date -> string
*
* @param builder
* @return
*/
@Bean
@Primary
@ConditionalOnMissingBean
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false)
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.timeZone(TimeZone.getTimeZone("Asia/Shanghai"))
.build();
//忽略未知字段
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//日期格式
SimpleDateFormat outputFormat = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
objectMapper.setDateFormat(outputFormat);
SimpleModule simpleModule = new SimpleModule();
/**
* 将Long,BigInteger序列化的时候,转化为String
*/
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
simpleModule.addSerializer(BigInteger.class, ToStringSerializer.instance);
simpleModule.addSerializer(BigDecimal.class, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
return objectMapper;
}
public static void buidMvcMessageConverter(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
ObjectMapper objectMapper = new ObjectMapper()
.registerModule(new ParameterNamesModule())
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule())
.registerModule(simpleModule);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
jackson2HttpMessageConverter.setObjectMapper(objectMapper);
converters.add(jackson2HttpMessageConverter);
}
@Override
public JsonSerializer<?> findSerializer(SerializationConfig config,
JavaType type, BeanDescription beanDesc)
{
Class<?> raw = type.getRawClass();
if (Duration.class.isAssignableFrom(raw) || QName.class.isAssignableFrom(raw)) {
return ToStringSerializer.instance;
}
if (XMLGregorianCalendar.class.isAssignableFrom(raw)) {
return XMLGregorianCalendarSerializer.instance;
}
return null;
}
@Override
public JsonSerializer<?> findSerializer(SerializationConfig config, JavaType type,
BeanDescription beanDesc, JsonFormat.Value formatOverrides)
{
Class<?> raw = type.getRawClass();
if (RangeSet.class.isAssignableFrom(raw)) {
return new RangeSetSerializer();
}
if (Range.class.isAssignableFrom(raw)) {
return new RangeSerializer(_findDeclared(type, Range.class));
}
if (Table.class.isAssignableFrom(raw)) {
return new TableSerializer(_findDeclared(type, Table.class));
}
if (HostAndPort.class.isAssignableFrom(raw)) {
return ToStringSerializer.instance;
}
if (InternetDomainName.class.isAssignableFrom(raw)) {
return ToStringSerializer.instance;
}
// not sure how useful, but why not?
if (CacheBuilderSpec.class.isAssignableFrom(raw) || CacheBuilder.class.isAssignableFrom(raw)) {
return ToStringSerializer.instance;
}
if (HashCode.class.isAssignableFrom(raw)) {
return ToStringSerializer.instance;
}
if (FluentIterable.class.isAssignableFrom(raw)) {
JavaType iterableType = _findDeclared(type, Iterable.class);
return new StdDelegatingSerializer(FluentConverter.instance, iterableType, null, null);
}
return null;
}
public InetJsonModule() {
super(InetJsonModule.class.getSimpleName(), new Version(1, 0, 0, null, null, null));
addSerializer(InetSocketAddress.class, ToStringSerializer.instance);
addDeserializer(InetSocketAddress.class, new FromStringDeserializer<InetSocketAddress>(InetSocketAddress.class) {
private static final long serialVersionUID = 1L;
@Override
protected InetSocketAddress _deserialize(String value, DeserializationContext ctxt) {
return InetSocketAddressConverter.getInetSocketAddress(value);
}
});
}
public TerracottaJsonModule() {
super(TerracottaJsonModule.class.getSimpleName(), new Version(1, 0, 0, null, null, null));
addSerializer(Path.class, ToStringSerializer.instance);
addDeserializer(Path.class, new FromStringDeserializer<Path>(Path.class) {
private static final long serialVersionUID = 1L;
@Override
protected Path _deserialize(String value, DeserializationContext ctxt) {
return Paths.get(value);
}
});
}
/**
* Get the IP Address for the switch
* @return the inet address
*/
@Override
@JsonSerialize(using=ToStringSerializer.class)
public SocketAddress getInetAddress() {
if (channel == null)
return null;
return channel.getRemoteAddress();
}
public static ObjectMapper create(boolean indent) {
ObjectMapper objectMapper = new ObjectMapper();
// This will cause the objectmapper to not close the underlying output stream
objectMapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
objectMapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
objectMapper.registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.SECONDS, false, MetricFilter.ALL));
SimpleModule module = new SimpleModule();
module.addSerializer(ExtendedMeter.class, new ExtendedMeterSerializer(TimeUnit.SECONDS));
module.addSerializer(BigDecimal.class, new ToStringSerializer());
objectMapper.registerModule(module);
if (indent) {
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
}
return objectMapper;
}
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = jackson2HttpMessageConverter.getObjectMapper();
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
SimpleModule simpleModule = new SimpleModule();
// Long类型序列化成字符串,避免Long精度丢失
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
// XSS序列化
simpleModule.addSerializer(String.class, new XssJacksonSerializer());
simpleModule.addDeserializer(String.class, new XssJacksonDeserializer());
// Date序列化
simpleModule.addSerializer(Date.class, new JacksonDateSerializer());
simpleModule.addDeserializer(Date.class, new JacksonDateDeserializer());
// Integer、Double反序列化
simpleModule.addDeserializer(Integer.class, new JacksonIntegerDeserializer());
simpleModule.addDeserializer(Double.class, new JacksonDoubleDeserializer());
// jdk8日期序列化和反序列化设置
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN)));
javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN)));
javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN)));
javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN)));
objectMapper.registerModule(simpleModule)
.registerModule(javaTimeModule).registerModule(new ParameterNamesModule());
jackson2HttpMessageConverter.setObjectMapper(objectMapper);
//放到第一个
converters.add(0, jackson2HttpMessageConverter);
}
@JsonSerialize(using=ToStringSerializer.class)
public Long getId() {
return id;
}
@JsonSerialize(using = ToStringSerializer.class)
@JsonProperty
public Duration lifetime() {
return this.lifetime.elapsed();
}
@SupCol(text="归属公司", sort = 10, minWidth="125px")
@JsonSerialize(using = ToStringSerializer.class)
public Office getOffice() {
return office;
}
@JsonSerialize(using = ToStringSerializer.class) @JsonProperty("amount")
public BigDecimal getAmount() {
return amount;
}
@JsonProperty
@JsonSerialize(using = ToStringSerializer.class)
public boolean isEnabled() {
return enabled;
}
@JsonProperty("stacktrace")
@JsonSerialize(contentUsing = ToStringSerializer.class)
StackTraceElement[] getStackTrace();
@JsonSerialize(using = ToStringSerializer.class)
@Nonnull
public DependencyType getType() {
return type;
}
@JsonSerialize(using = ToStringSerializer.class) @JsonProperty("amount")
public BigDecimal getAmount() {
return amount;
}
@AdditionalJacksonAnnotation("some_long")
@JsonProperty("some_long_string")
@JsonSerialize(using=ToStringSerializer.class)
Long getSomeLong();
/**
* @return The network associated with the record. In particular, this is
* the largest network where all of the fields besides IP address have the
* same value.
*/
@JsonProperty
@JsonSerialize(using = ToStringSerializer.class)
public Network getNetwork() {
return this.network;
}
/**
* @return The network associated with the record. In particular, this is
* the largest network where all of the fields besides IP address have the
* same value.
*/
@JsonProperty
@JsonSerialize(using = ToStringSerializer.class)
public Network getNetwork() {
return this.network;
}