我有这样一个实体:
public class User {
private Long id;
private String email;
private String password;
private List<Role> roles;
//set of constructors, getters, setters...
和相关的JSON:
[
{
"email": "user@email",
"roles": ["REGISTERED_USER"]
}
]
我试图以这种方式在Spring MVC @Controller中反序列化它:
List<User> users = Arrays.asList(objectMapper.readValue(multipartFile.getBytes(), User[].class));
在添加List<Role>
之前,它完美无缺,但在我还没有运气之后。看来我需要一些自定义反序列化器,你能帮忙解决一下吗?谢谢!
答案 0 :(得分:2)
如果您有权访问Role类,则只需添加此类构造函数:
private Role(String role) {
this.role = role;
}
或静态工厂方法:
@JsonCreator
public static Role fromJson(String value){
Role role = new Role();
role.setRole(value);
return role;
}
@JsonValue
public String toJson() {
return role;
}
否则你将不得不编写自定义deserealizer并在对象映射器上注册它,如下所示:
public static class RoleSerializer extends JsonSerializer {
@Override
public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
gen.writeString(((Role) value).getRole());
}
}
public static class RoleDeserializer extends JsonDeserializer {
@Override
public Role deserialize(JsonParser jsonParser,DeserializationContext deserializationContext) throws IOException {
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
Role role = new Role();
role.setRole(node.asText());
return role;
}
}
以下是演示:https://gist.github.com/varren/84ce830d07932b6a9c18
FROM:[{&#34; email&#34;:&#34; user @ email&#34;,&#34; roles&#34;:[&#34; REGISTERED_USER&#34;]}]
TO OBJ:[用户{id = null,电子邮件=&#39;用户@电子邮件&#39;,密码=&#39; null&#39;,roles =角色{role =&#39; REGISTERED_USER&#39 ;}}]
TO JSON:[{&#34; email&#34;:&#34; user @ email&#34;,&#34; role&#34;:[&#34; REGISTERED_USER&#34;]}] < / p>
PS: 如果你像这样使用ObjectMapper
Arrays.asList(objectMapper.readValue(multipartFile.getBytes(), User[].class));
然后来自demo的代码将起作用,但是您可能必须在Spring中为jackson ObjectMapper设置自定义Bean,以使RoleDeserializer和RoleSerializer在任何地方都可以工作。这是更多信息: Spring, Jackson and Customization (e.g. CustomDeserializer)