本文共 4040 字,大约阅读时间需要 13 分钟。
com.fasterxml.jackson.core jackson-annotations 2.8.6 com.fasterxml.jackson.core jackson-databind 2.8.6
package com.paascloud.helper;import com.fasterxml.jackson.core.JsonGenerator;import com.fasterxml.jackson.databind.JsonSerializer;import com.fasterxml.jackson.databind.SerializerProvider;import java.io.IOException;/** * Long 类型字段序列化时转为字符串,避免js丢失精度 */public class LongJsonSerializer extends JsonSerializer{ /** * Serialize. * * @param value the value * @param jsonGenerator the json generator * @param serializerProvider the serializer provider * * @throws IOException the io exception */ @Override public void serialize(Long value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { String text = (value == null ? null : String.valueOf(value)); if (text != null) { jsonGenerator.writeString(text); } }}
package com.paascloud.helper;import com.fasterxml.jackson.core.JsonParser;import com.fasterxml.jackson.databind.DeserializationContext;import com.fasterxml.jackson.databind.JsonDeserializer;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.IOException;/** * 将字符串转为Long */public class LongJsonDeserializer extends JsonDeserializer{ private static final Logger logger = LoggerFactory.getLogger(LongJsonDeserializer.class); /** * Deserialize long. * * @param jsonParser the json parser * @param deserializationContext the deserialization context * * @return the long * */ @Override public Long deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) { String value = null; try { value = jsonParser.getText(); } catch (IOException e) { e.printStackTrace(); } try { return value == null ? null : Long.parseLong(value); } catch (NumberFormatException e) { logger.error("解析长整形错误", e); return null; } }}
@Datapublic class BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @JsonSerialize(using = LongJsonSerializer.class) @JsonDeserialize(using = LongJsonDeserializer.class) private Long id;}
发现在List中还有问题
org.apache.rocketmq rocketmq-client 4.1.0-incubating de.codecentric spring-boot-admin-starter-client org.springframework.boot spring-boot-starter-freemarker org.springframework.cloud spring-cloud-starter-feign
@Bean public ObjectMapper ObjectMapper(){ 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);// SerializerProvider serializerProvider = objectMapper.getSerializerProvider();// serializerProvider.setNullValueSerializer(new JsonSerializer
小坑一个记录一下, 解决现有问题
转载地址:http://xvcwo.baihongyu.com/