質問

Lets say I have a JSON:

{

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

I got:

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

But that works when moviesListArrayString is:

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

if my String is the original JSON, how can I tell Jackson to ignore MovieCount and deserialize MoviesList?

役に立ちましたか?

解決 2

One solution can be to read the full JSON as a JsonNode and only deserialize what you are interested in:

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

他のヒント

I would create a wrapper object with two properties:

  • Number movieCount
  • List<Movie> moviesList

Then read the value as YourWrapperObject.class and do whatever you need to do with the moviesList property value, while ignoring the moviecount property.

Quick, very ugly but functional example

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 {

    }

}

Output

2
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top