对于JSON对象,Subject
:
{
"permissions":["foo", "bar"],
...
}
...我想反序列化为:
class Subject {
private List<Permission> permissions;
...
...其中Permission
是:
class Permission {
....
public Permission(String permission) {
....
}
Permission
不是我控制的类,所以我只有构造函数来处理。
我确信杰克逊可以做到这一点,但我还是不相信我找到了最好的方法。我对ArrayDeserializer
和@JsonDeserialize(contentAs = Permission.class)
的努力失败了,在我开始继承JsonDeserializer
之前,我想验证没有内置功能可以做到这一点。
答案 0 :(得分:6)
结束编写我自己的反序列化器。
public class PermissionDeserializer extends JsonDeserializer<List<Permission>> {
@Override
public List<Permission> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
if (jsonParser.getCurrentToken() == JsonToken.START_ARRAY) {
List<Permission> permissions = new ArrayList<>();
while(jsonParser.nextToken() != JsonToken.END_ARRAY) {
permissions.add(new Permission(jsonParser.getValueAsString()));
}
return permissions;
}
throw deserializationContext.mappingException("Expected Permissions list");
}
}
答案 1 :(得分:1)
以下是一个指导您的示例。
<强> Subject.java 强>
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class Subject {
public static void main(String[] args) throws Exception, JsonMappingException, IOException {
String json = "{\"permissions\":[\"foo\", \"bar\"]}";
ObjectMapper mapper = new ObjectMapper();
Subject subject = mapper.readValue(json, Subject.class);
for(Permission p:subject.getPermissions()){
System.out.println(p.getPermission());
}
}
private List<Permission> permissions = new ArrayList<Permission>();
public List<Permission> getPermissions() {
return permissions;
}
public void setPermissions(List<Permission> permissions) {
this.permissions = permissions;
}
}
<强> Permission.java 强>
class Permission {
private String permission;
public Permission(String permission) {
this.permission = permission;
}
public String getPermission() {
return permission;
}
public void setPermission(String permission) {
this.permission = permission;
}
}