Jackson在json序列化时经常有用到,也会有一些序列化异常需要注意的,比如我们使用jackson将一段json字符串转化为User实体类的时候,如下所示:
ObjectMapper mapper = new ObjectMapper(); User user = mapper.readValue(jsonStr, User.class);
此时在转化User实体类的时候,可能会出现如下的错误:
Exception in thread "main"
com.fasterxml.jackson.databind.JsonMappingException: Can not construct
instance of sample.User: no suitable constructor found, can not
deserialize from Object value (missing default constructor or creator,
or perhaps need to add/enable type information?)
解决方案:
出现上面的错误,是因为我们的User实体类没有构造方法所致,这种情况比较少,所以我们在User实体类加上无参构造方法即可,如下:
public class User { private String firstName; private String lastName; private Date dateOfBirth; private List<String> emailAddrs; //加入构造方法 public User() {} ... }
在Jackson将Json格式转化为实体类的时候,有时候也会遇到这样的错误:
Exception in thread "main"
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:
Unrecognized field "gender" (class sample.User), not marked as
ignorable (6 known properties: ...)
解决方案:
出现这种异常是因为你的json字符串里面包含了一些在Java实体类中未定义的属性,因此我们需要ignore忽略这些字段,这样就可以防止json中有一些未知的字段造成转换实体类时出现上述的错误,在实体类中加入如下注解即可:
@JsonIgnoreProperties(ignoreUnknown=true) public class User { ... }