版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/meifannao789456/article/details/89403287
在Spring开发中,我们经常使用Jackson进行Json数据和Bean对象之间的序列化和反序列化。Json数据和Bean对象之间一一对应,转化起来非常方便。
但是,如果我们有一个Child
父类,有两个类Son
和Daughter
继承Child
父类
public Class Child {
private String type; // son or daughter
}
public Class Son extends Child {
}
public Class Daughter extends Child {
}
我们需要根据Json
数据中的type来判断转化成哪个Bean对象。如果type=son
,则生成Son对象,如果type=daughter
,则生成Daughter。
我们需要使用StdDeserializer
来自定义反序列化规则,Child实现如下:
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import java.io.IOException;
public class Child {
private String type;
public Child() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public static class ChildDeserializer extends StdDeserializer<Child> {
protected ChildDeserializer() {
super(Child.class);
}
@Override
public Child deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
String type = node.get("type").asText();
if (type.equalsIgnoreCase("son")) {
Child child = mapper.readValue(node.toString(), Son.class);
return child;
}else if (type.equalsIgnoreCase("daughter")) {
Child child = mapper.readValue(node.toString(), Daughter.class);
return child;
}
return mapper.readValue(node.toString(), Child.class);
}
}
}
通过type的值来使用不同的类来反序列化。
在我们声明Child
的地方加上注解@JsonDeserialize
:
public class ChildReq {
@JsonDeserialize(using = Child.ChildDeserializer.class)
private Child child;
}
在Spring的Controller中:
@PostMapping("/child")
@ApiIgnore
@ValidParam
public Object child(@RequestBody String json) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
ChildReq req = mapper.readValue(json, ChildReq.class);
}
这样就可以根据type类型,自动反序列化成对应的子类来。
扫码关注微信公众号,更好的交流