目录
导言
有的时候在定义实体类的时候忘记写无参构造器了,或者必须不能有无参构造方法,那这时我们反序列化会有一定的问题,因为像FastJSON中对于不含有无参构造方法的类反序列化是不太容易实现的,但是我们可以通过Jackson来实现。
举例说明
比如我们有这样一个用户类,它不含有无参构造方法
public class UserProfile {
private String name;
private String profilePicture;
private String email;
public UserProfile(String name, String profilePicture, String email) {
this.name = name;
this.profilePicture = profilePicture;
this.email = email;
}
public String getName() {
return name;
}
public String getProfilePicture() {
return profilePicture;
}
public String getEmail() {
return email;
}
}
我们需要对下面数据进行反序列化:
{
"name": "Dummy",
"profilePicture": "http://picturesource",
"email": "dummy@myblogspro.com"
}
方案一 自定义Jackson反序列化器
public class UserProfileDeserializer extends JsonDeserializer<UserProfile> {
@Override
public UserProfile deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
String EMPTY_STRING = "";
JsonNode node = jsonParser.readValueAsTree();
String name = node.has("name") ? node.get("name").asText() : EMPTY_STRING;
String profilePic = node.has("profilePicture") ? node.get("profilePicture").asText() : EMPTY_STRING;
String email = node.has("email") ? node.get("email").asText() : EMPTY_STRING;
return new UserProfile(name, profilePic, email);
}
}
测试代码
public class UserProfileDeserializerDemo {
public static void main(String[] args) throws IOException {
// MyBlogsPro is just module name. You can choose your own name
SimpleModule module = new SimpleModule("MyBlogsPro");
module.addDeserializer(UserProfile.class, new UserProfileDeserializer());
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);
// TODO: 12/9/16 Pass your json string/source as first parameter in below method
UserProfile profile = mapper.readValue("{\n" +
" \"name\": \"Dummy\",\n" +
" \"profilePicture\": \"http://picturesource\",\n" +
" \"email\": \"dummy@myblogspro.com\"\n" +
"}", UserProfile.class);
System.out.println(profile.getName());
}
}
方案二 使用MixIn注解方式
建立MixIn抽象类
public abstract class UserProfileMixin {
@JsonCreator
public UserProfileMixin(@JsonProperty("name") String name, @JsonProperty("profilePicture") String profilePicture,
@JsonProperty("email") String email) {
}
}
测试代码
public class DeserializerAddMixInDemo {
public static void main(String[] args) throws Exception{
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(UserProfile.class, UserProfileMixin.class);
// TODO: 12/9/16 Pass your json string/source as first parameter in below method
UserProfile profile = mapper.readValue("{\n" +
" \"name\": \"Dummy\",\n" +
" \"profilePicture\": \"http://picturesource\",\n" +
" \"email\": \"dummy@myblogspro.com\"\n" +
"}", UserProfile.class);
System.out.println("Name:"+ profile.getName());
}
}