如何使用Jackson将JSON反序列化为忽略密钥的对象?

时间:2014-05-07 15:53:20

标签: java json jackson

假设我有一个JSON:

{

"MovieCount": 153,
"MoviesList": [{...},{...},...]
}

我得到了:

mapper.readValue(moviesListArrayString, new TypeReference<List<Movie>>(){});

但是moviesListArrayString是:

[{...},{...},...]

如果我的 String 是原始JSON,我怎么能告诉杰克逊忽略 MovieCount 并反序列化 {{1} }

2 个答案:

答案 0 :(得分:3)

我会创建一个包含两个属性的包装器对象:

  • Number movieCount
  • List<Movie> moviesList

然后将值读作YourWrapperObject.class,并对moviesList属性值执行任何操作,同时忽略moviecount属性。

快速,非常丑陋但功能性的例子

package test;

import java.util.List;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {

    public static void main(String[] args) {
        ObjectMapper mapper = new ObjectMapper();

        String json = "{\"MovieCount\": 153,\"MoviesList\": [{},{}]}";
        try {
            List<Movie> movies = ((MovieWrapper) mapper.readValue(json, MovieWrapper.class)).moviesList;
            System.out.println(movies.size());
        }
        catch (Throwable t) {
            t.printStackTrace();
        }

    }

    static class MovieWrapper {

        @JsonProperty(value = "MovieCount")
        int movieCount;
        @JsonProperty(value = "MoviesList")
        List<Movie> moviesList;
    }

    static class Movie {

    }

}

<强>输出

2

答案 1 :(得分:2)

一种解决方案可以是将完整的JSON读作JsonNode,只反序列化您感兴趣的内容:

final JsonNode node = mapper.readTree(...);
movieList = mapper.readValue(node.get("MoviesList").traverse(), typeRefHere);