使用Jackson将嵌套数组反序列化为ArrayList

24

我有一段 JSON,看起来像这样:

{
  "authors": {
    "author": [
      {
        "given-name": "Adrienne H.",
        "surname": "Kovacs"
      },
      {
        "given-name": "Philip",
        "surname": "Moons"
      }
    ]
   }
 }

我创建了一个类来存储作者信息:

public class Author {
    @JsonProperty("given-name")
    public String givenName;
    public String surname;
}

还有两个包装类:

public class Authors {
    public List<Author> author;
}

public class Response {
    public Authors authors;
}

这个代码可以正常工作,但似乎有两个包装类是不必要的。我想找到一种方法来删除 Authors 类,并将列表作为 Entry 类的属性。使用 Jackson 是否可能实现这样的功能?

更新

通过自定义反序列化器解决了这个问题:

public class AuthorArrayDeserializer extends JsonDeserializer<List<Author>> {

    private static final String AUTHOR = "author";
    private static final ObjectMapper mapper = new ObjectMapper();
    private static final CollectionType collectionType =
            TypeFactory
            .defaultInstance()
            .constructCollectionType(List.class, Author.class);

    @Override
    public List<Author> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
            throws IOException, JsonProcessingException {

        ObjectNode objectNode = mapper.readTree(jsonParser);
        JsonNode nodeAuthors = objectNode.get(AUTHOR);

        if (null == nodeAuthors                     // if no author node could be found
                || !nodeAuthors.isArray()           // or author node is not an array
                || !nodeAuthors.elements().hasNext())   // or author node doesn't contain any authors
            return null;

        return mapper.reader(collectionType).readValue(nodeAuthors);
    }
}

并且像这样使用它:

@JsonDeserialize(using = AuthorArrayDeserializer.class)
public void setAuthors(List<Author> authors) {
    this.authors = authors;
}

感谢 @wassgren 的建议。

这个回答对你有帮助吗? - Ankur Singhal
1个回答

18

如果你想摆脱包装类,至少有两种方法可以做到。第一种是使用Jackson树模型(JsonNode),第二种是使用一个叫做UNWRAP_ROOT_VALUE的反序列化功能。


替代方案1:使用JsonNode

在使用Jackson解析JSON时,有多种方法可以控制创建什么类型的对象。 ObjectMapper 可以将JSON反序列化为例如一个 MapJsonNode(通过 readTree 方法)或POJO。

如果结合 readTree 方法和 POJO 转换,则可以完全删除包装类。示例:

// The author class (a bit cleaned up)
public class Author {
    private final String givenName;
    private final String surname;

    @JsonCreator
    public Author(
            @JsonProperty("given-name") final String givenName,
            @JsonProperty("surname") final String surname) {

        this.givenName = givenName;
        this.surname = surname;
    }

    public String getGivenName() {
        return givenName;
    }

    public String getSurname() {
        return surname;
    }
}

反序列化过程可以像这样:

// The JSON
final String json = "{\"authors\":{\"author\":[{\"given-name\":\"AdrienneH.\",\"surname\":\"Kovacs\"},{\"given-name\":\"Philip\",\"surname\":\"Moons\"}]}}";

ObjectMapper mapper = new ObjectMapper();

// Read the response as a tree model
final JsonNode response = mapper.readTree(json).path("authors").path("author");

// Create the collection type (since it is a collection of Authors)
final CollectionType collectionType =
        TypeFactory
                .defaultInstance()
                .constructCollectionType(List.class, Author.class);

// Convert the tree model to the collection (of Author-objects)
List<Author> authors = mapper.reader(collectionType).readValue(response);

// Now the authors-list is ready to use...
如果您使用这个树模型方法,包装类可以完全被移除。
备选方案2:移除其中一个包装器并取消根值的包装 第二种方法是仅删除一个包装器。假设您删除了Authors类但保留了Response包装器。如果您添加@JsonRootName注释,稍后可以取消顶层名称的包装。
@JsonRootName("authors") // This is new compared to your example
public class Response {
    private final List<Author> authors;

    @JsonCreator
    public Response(@JsonProperty("author") final List<Author> authors) {
        this.authors = authors;
    }

    @JsonProperty("author")
    public List<Author> getAuthors() {
        return authors;
    }
}

然后,对于您的映射器,只需使用以下代码:

ObjectMapper mapper = new ObjectMapper();

// Unwrap the root value i.e. the "authors"
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
final Response responsePojo = mapper.readValue(json, Response.class);

第二种方法仅移除其中一个包装类,但解析函数非常简洁。


我使用了备选方案2,结果非常顺利。 - Vilas Paskanti

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接