Jackson ObjectMapper 使用教程
添加 依赖gradleimplementation("com.fasterxml.jackson.dataformat:jackson-dataformat-xml")maven<dependency><groupId>com.fasterxml.jackson.dataformat</groupId><artifactId>jackson-data
·
添加 依赖
gradle
implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-xml")
maven
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.8.2</version>
</dependency>
配置 ObjectMapper
/**
* Jackson config
* @return 自定义 {@link com.fasterxml.jackson.databind.ObjectMapper} 配置
*/
@Bean
public Jackson2ObjectMapperBuilderCustomizer objectMapperBuilderCustomizer() {
return builder -> {
// 序列化时字段值为 null 时不输出
builder.serializationInclusion(JsonInclude.Include.NON_NULL);
// 序列化时按照字幕顺序输出(降低点性能,但是关键时刻方便进行字段对比)
builder.featuresToEnable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY);
// 有不匹配的字段是否抛出异常
builder.featuresToDisable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
// 接受单个字符的值反序列化为数组。
builder.featuresToEnable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
// 配置 时间序列化
builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
builder.serializerByType(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
builder.serializerByType(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
builder.serializerByType(Date.class, new DateSerializer(false, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));
builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
builder.deserializerByType(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
builder.deserializerByType(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
builder.deserializerByType(Date.class, new DateDeserializers.DateDeserializer(DateDeserializers.DateDeserializer.instance, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss"));
};
}
Jackson 的注解使用
序列化生效 实体转为json
反序列化生效 json转为实体类
序列化生效
@JsonProperty("名字key")
public String name; //{"名字key":"张三"}
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy/MM/dd HH:mm:ss", locale = "zh", timezone = "GMT+8")
private Date profileCreateTime; //{"profileCreateTime":"2018/12/7 12:30:00"}
反序列化生效
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public static class aBean {}
// 放在类名上面 则对此类全部属性起作用 序列化或往页面传值时起作用
JsonInclude.Include.ALWAYS 默认不生效 序列化
JsonInclude.Include.NON_NULL 属性为NULL 不序列化
JsonInclude.Include.NON_ABSENT 属性为空字符串 不序列化
JsonInclude.Include.NON_EMPTY 属性为空字符串 或 NULL 不序列化
JsonInclude.Include.NON_DEFAULT 属性为默认值时 不序列化
JsonInclude.Include.CUSTOM 指定自定义筛选器 不序列化
JsonInclude.Include.USE_DEFAULTS 使用类或对象的默认值 序列化
//自定义 序列化 处理
@JsonSerialize(using = Data2LongSerizlizer.class )
public class Data2LongSerizlizer extends JsonSerializer<Date> {
@Override
/** 该类可以将日期13位时间戳转换成10位时间戳的long类型 */
}
//反序列化期间接受的属性定义一个或多个替代名称, 序列化时候还是取 userName
@JsonAlias({"aName", "bName"})
private String userName;
ObjectMapper 的简单使用
@Resource
private ObjectMapper objectMapper;
Person person = new Person();
entity 转 string json 如果有@JsonSerialize("") ,key 就取的是这个的值
```java
String personString =objectMapper.writeValueAsString(person));
string json [{“a”:2},{“a”:4}] 转 list
List<Person> plist = objectMapper.readValue(personString , new TypeReference<List<.Person>>(){});
string json {“a”:2} 转 entity
Person p= objectMapper.readValue(personString , Person.class);
string json {“a”:2} 转 Map
TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {};
HashMap<String, Object> o = objectMapper.readValue(value, typeRef);
更新对象的值 将personString 值 覆盖部分有的属性. entity
ObjectReader objectReader = objectMapper.readerForUpdating(person);
Person updatedPerson = objectReader.readValue(personString);
entity 转 jsonObject 如果有@JsonSerialize("") ,key 就取的是这个的值
objectMapper.convertValue(personString, JSONObject.class);
string json 转 person Node
JsonNode actualObj = objectMapper.readTree(personString);
@JsonRawValue 防止添加多余的内容\r\n 转换成原始对象
in
{
"name" : "Mark",
"rollNo" : 1,
"json" : {\"attr\":false}
}
@JsonRawValue
private String json;
out
{
"name" : "Mark",
"rollNo" : 1,
"json" : {"attr":false}
}
例子 ,数据库存的 jons 字符串 页面想返回 对象
//因为全局 配置 ,所以要先判断下是否为 字符串
public class StringSerializer extends JsonSerializer<String> {
@Resource
private ObjectMapper objectMapper;
@Override
public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
boolean flag = false;
if (StringUtils.isNotBlank(value)) {
value = value.trim();
if (value.startsWith("{") && value.endsWith("}")) {
flag = true;
}
if (value.startsWith("[") && value.endsWith("]")) {
flag = true;
}
if (value.startsWith("[{") && value.endsWith("}]")) {
flag = true;
}
}
if (flag) {
try {
objectMapper.readTree(value);
flag = true;
} catch (Exception e) {
flag = false;
}
if (flag) {
TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {};
HashMap<String, Object> o = objectMapper.readValue(value, typeRef);
gen.writeObject(o);
}
}
gen.writeString(value);
}
}
全局配置
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
objectMapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
SimpleModule simpleModule = new SimpleModule();
// simpleModule.addDeserializer(String.class, new StringDeserializer());
simpleModule.addSerializer(String.class, new StringSerializer());
objectMapper.registerModule(simpleModule);
jsonConverter.setObjectMapper(objectMapper);
return jsonConverter;
}
复杂对象json 转换 (泛型)
例子 jsonSting to ObjectEntity
json = "{
"code": 0,
"msg": null,
"obj": {
"current": 1,
"hitCount": false,
"optimizeCountSql": true,
"orders": [],
"pages": 1,
"records": [
{
"address": "海南省三亚市海棠区",
"deviceId": "8880139",
"deviceName": "海南省三亚市海棠区微心测试",
"hospitalId": 12,
"hospitalName": "测试专用医院",
"id": 896,
"lat": 18.34801783549779,
"lng": 109.71318002841308,
"status": 1,
"updateTime": 1602228247000
},
{
"address": "北站",
"deviceId": "80801108",
"deviceName": "测试设备1",
"hospitalId": 12,
"hospitalName": "测试专用医院",
"id": 895,
"lat": 30.21715956845446,
"lng": 115.01468563671428,
"status": 1,
"updateTime": 1601374004000
}
],
"searchCount": true,
"size": 500,
"total": 11
}
}";
JavaType javaType1 = objectMapper.getTypeFactory().constructParametricType(Page.class, DeviceEntity.class);
JavaType javaTyp = objectMapper.getTypeFactory().constructParametricType(JsonResult.class,javaType1);
TypeReference<JsonResult<Page<DeviceEntity>>> typeReference = new TypeReference<JsonResult<Page<DeviceEntity>>>() {};
//通过 javaType 转换
JsonResult<Page<DeviceEntity>> page1 = objectMapper.readValue(json,javaTyp);
// 通过 TypeReference 来转换
JsonResult<Page<DeviceEntity>> page2 = objectMapper.readValue(json,typeReference);
public class JsonResult<T> implements Serializable {
private static final long serialVersionUID = 7982365785632121536L;
private int code;
private T obj;
private String msg;
}
public class Page<T> implements IPage<T> {
private static final long serialVersionUID = 8545996863226528798L;
/**
* 查询数据列表
*/
private List<T> records = Collections.emptyList();
/**
* 总数
*/
private long total = 0;
/**
* 每页显示条数,默认 10
*/
private long size = 10;
/**
* 当前页
*/
private long current = 1;
/**
* 排序字段信息
*/
private List<OrderItem> orders = new ArrayList<>();
/**
* 自动优化 COUNT SQL
*/
private boolean optimizeCountSql = true;
/**
* 是否进行 count 查询
*/
private boolean isSearchCount = true;
}
@Data
public class DeviceEntity implements Serializable {
@ApiModelProperty(value = "ID")
@JsonProperty("id")
Integer id;
@ApiModelProperty(value = "设备ID")
@JsonProperty("deviceId")
String deviceId;
@ApiModelProperty(value = "设备名称")
@JsonProperty("deviceName")
String deviceName;
@ApiModelProperty(value = "设备地址")
@JsonProperty("address")
String address;
@ApiModelProperty(value = "设备管理员名称")
@JsonProperty("manager")
String manager;
@ApiModelProperty(value = "设备管理员电话")
@JsonProperty("phone")
String phone;
@ApiModelProperty(value = "所属医院Id")
@JsonProperty("hospitalId")
Integer hospitalId;
@ApiModelProperty(value = "所属医院名称")
@JsonProperty("hospitalName")
String hospitalName;
@ApiModelProperty(value = "是否有效")
@JsonProperty("status")
Integer status;
@ApiModelProperty(value = "新增或更新时间")
@JsonProperty("updateTime")
Date updateTime;
@ApiModelProperty(value = "纬度值")
@JsonProperty("lat")
Double lat;
@ApiModelProperty(value = "经度值")
@JsonProperty("lng")
Double lng;
}
更多推荐
已为社区贡献3条内容
所有评论(0)