一直使用jackson处理json,最近ui传来的数据{"funcCode":"Read_Coils","action":"pass","startaddr":"","endaddr":""},处理时需要把""转为null,
看了许久才明白其中的道理.
先写一个自定义反序列化类
-
import com.fasterxml.jackson.core.JsonParser;
-
import com.fasterxml.jackson.core.JsonProcessingException;
-
import com.fasterxml.jackson.databind.DeserializationContext;
-
import com.fasterxml.jackson.databind.JsonDeserializer;
-
import com.fasterxml.jackson.databind.JsonNode;
-
-
import java.io.IOException;
-
-
/**
-
* Created by li on 2/17/17.
-
*/
-
class CustomDeserializer extends JsonDeserializer<String> {
-
-
@Override
-
public String deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JsonProcessingException {
-
JsonNode node = jsonParser.readValueAsTree();
-
if (node.asText().isEmpty()) {
-
return null;
-
}
-
return node.toString();
-
}
-
-
}
然后在POJO类需要转换的字段加注解
-
private String action;
-
@JsonDeserialize(using = CustomDeserializer.class)
-
private String startaddr;
-
@JsonDeserialize(using = CustomDeserializer.class)
-
private String endaddr;
主要是引用
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
转换的代码
-
ObjectMapper mapper = new ObjectMapper();
-
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
-
-
ModbusTcp modbusTcp = mapper.readValue(json, ModbusTcp.class);
导入库
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
注意是fastxml不是codehua,否则不起作用
阅读(17743) | 评论(0) | 转发(1) |