What I want to do is , when I navigate to:
http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=[your_api_key]&q=Toy+Story+3&page
You have a mix of basic Java programming and JSON mapping errors. First of all, remember to follow lower camel case naming conventions when defining your Java classes. Not only is it a best practice but more importantly, several tools and libraries will not work if you do not follow this pattern (Jackson included).
As far as your JSON mapping errors, the most important thing to keep in mind when mapping JSON to Java objects is that JSON data is effectively a map. It associates keys with values, where the values can be primitives, objects, or arrays (collection). So, given a JSON structure you have to look at the structure of each keys value, then decide wether that value should be represented in Java as a primitive, an object, or as an array of either. No shortcuts to this, you will learn by experience. Here is an example:
{
"total": 1, // maps to primitive, integer
"movies": [ // '[' marks the beginning of an array/collection
{ // '{' marks the beginning of an object
"id": "770672122", // maps to primitive, string
"title": "Toy Story 3",
"year": 2010,
"mpaa_rating": "G",
"runtime": 103,
"release_dates": { // each array object also contains another object
"theater": "2010-06-18",
"dvd": "2010-11-02"
}
}
]
}
When mapping the example JSON above, you need to define a root object that matches the outermost {
. Lets call this root object a MovieResponse
.
public class MovieResponse {
}
Now, walking down the JSON data, we start to map over all the JSON attributes to Java properties:
@JsonIgnoreProperties(ignoreUnknown = true)
public class MovieResponse {
private Integer total; // map from '"total": 1'
private List<Movie> movies; // map from '"movies": [', remember, its a collection
}
Simple right? But of course, we also need to define a structure for the Movie
class. Once again, walking the JSON:
@JsonIgnoreProperties(ignoreUnknown = true)
public class Movie {
private String id; // map from '"id": "770672122"'
private String title; // map from '"title": "Toy Story 3"'
private Integer year;
@JsonProperty("mpaa_rating")
private String mpaaRating;
private Integer runtime;
@JsonProperty("release_dates")
private Release released; // another object mapping!
}
And finally, map the inner-most object that represents release dates:
public class Release {
private String theater;
private String dvd;
}
Thats it, very straightforward. Note the use of @JsonProperty
in the Movie
class. It allows you to map an attribute from your JSON to a property in Java, with a different name. Also note that constructors/setters/getters were omitted from each of the classes above, for brevity. In your real code you would add them in. Finally, you would map the example JSON to the Java MovieResponse
class using the following code:
MovieResponse response = new ObjectMapper().readValue(json, MovieResponse.class);