The complete source code for the Java example can be found at GitHub. Clone the repository to get started.
git clone https://github.com/xmlstats/example-java.git
The example shows two ways to access the xmlstats API. One uses Apache HttpComponents
while the other uses java.net.*
packages. Both use Jackson
to deserialize the JSON response into POJOs.
If you are able to use 3rd party libraries, Apache HttpComponents is the recommended strategy since it
provides greater flexibility to build and process HTTP requests than the java.net.*
packages.
The example shows a glimpse of that. A full-featured program would also include working with the HTTP
headers and appropriately handling errors.
Plain Old Java Objects
Using the API documentation, POJOs can be created to map the JSON by way of the Jackson library.
Note that the entire JSON object does not need to be mapped. JSON properties can be ignored by using
the @JsonIgnoreProperties(ignoreUknown = true)
annotation at the class level. This means JSON
properties that do not exist in the POJO are skipped, otherwise Jackson throws a parse exception. We can
safely use this annotation to map only the properties we want and ignore the rest.
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class Event { }
The other annotation frequently used in the example, @JsonProperty(name)
,
instructs the Jackson ObjectMapper to map the JSON property name
to the annotated
Java field's name.
@JsonProperty("start_date_time") private String startDateTime;
The example that uses Apache HttpComponents also uses a
simple POJO
to handle any errors
returned from the xmlstats API service. Most errors returned by the service
will include an error code, typically the HTTP status code, and a more helpful description of what
went wrong. Nothing fancy here, but notice that the @JsonRootName
annotation informs Jackson
that the JSON includes a root value named error
.
import com.fasterxml.jackson.annotation.JsonRootName; @JsonRootName("error") public class XmlstatsError { }