json数据
{
"dataInfo": "{\"ticketBusinessType\": \"example\",\"ticket\": \"was\"}",
"businessId": "234"
}
问题:json中dataInfo是一个转义后的json本职上是string类型,所以无法使用hutool工具
JSONUtil.toBean(json, EventDTO.class);
进行一次性转化为Bean,会出现转换异常MismatchedInputException
,如何能实现一次性转化为EventDTO呢?
解决思路:自定义一个JsonDeserializer来处理这个转换过程
Bean的定义:
public class EventDTO {
private String businessId;
@JsonDeserialize(using = DataInfo.class)
private DataInfo dataInfo;
@Data
public static class DataInfo extends JsonDeserializer<DataInfo> {
private String ticketBusinessType;
@Override
public DataInfo deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
String dataInfoString = jsonParser.getText();
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(dataInfoString, EventDTO.DataInfo.class);
}
}
}
引发
UnrecognizedPropertyException
异常
原因:Jackson库在反序列化时要求DTO类中的字段和JSON中的属性名称一一对应。我们的json中有2个属性,bean定义了1个ticketBusinessType,因此报错
这种定义是很常见的,比如消费对方kafka数据,对方有50个属性,你只需要2个属性来做业务逻辑,无需定义50个属性值进行接收,那该如何来解决 反序列化时忽略JSON中的额外属性 呢
解决思路:在ObjectMapper中配置DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES为false即可
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
完整的bean定义
@Data
public class EventDTO {
private String businessId;
@JsonDeserialize(using = DataInfo.class)
private DataInfo dataInfo;
@Data
public static class DataInfo extends JsonDeserializer<DataInfo> {
/**
* 业务类型
*/
private String ticketBusinessType;
@Override
public DataInfo deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
String dataInfoString = jsonParser.getText();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return objectMapper.readValue(dataInfoString, EventDTO.DataInfo.class);
}
}
}
使用:
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
// 如果json中有新增的字段并且是实体类类中不存在的,不报错
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
EventDTO msg = mapper.readValue(message, new TypeReference<EventDTO>() {});