杰克逊:将字符串数组反序列化为List <t> </t>

时间:2013-12-11 10:06:30

标签: jackson deserialization

对于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之前,我想验证没有内置功能可以做到这一点。

2 个答案:

答案 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;
    }
}