[Java] Using Jackson and Jersey to parse a JSON file to an List

[Java] Using Jackson and Jersey to parse a JSON file to an List

This example will show you how to convert a JSON file into a JSON String, then parse it to ArrayList. Assuming I hava a timeZoneList.json file:

    "zoneID": "Pacific/Kwajalein",
    "offset": -12,
    "zoneName": "(GMT -12:00) Eniwetok, Kwajalein"
    "zoneID": "Pacific/Midway",
    "offset": -11,
    "zoneName": "(GMT -11:00) Midway Island, Samoa"
    "zoneID": "US/Hawaii",
    "offset": -10,
    "zoneName": "(GMT -10:00) Hawaii"
  .....(more timezone objects)

Then create a TimeZone.java. This is the Java class that is going to be represented in JSON format.

public class TimeZone {
	private String zoneID;
	private String zoneName;
	private int offset;

	public String getZoneID() {
		return zoneID;

	public void setZoneID(String zoneID) {
		this.zoneID = zoneID;

	public String getZoneName() {
		return zoneName;

	public void setZoneName(String zoneName) {
		this.zoneName = zoneName;

	public int getOffset() {
		return offset;

	public void setOffset(int offset) {
		this.offset = offset;

Create the following classes which will be used as REST resources, and convert JSON file into ArrayList.

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class TimeZoneList {

	public Response getTimeZoneList() throws JsonMappingException, JsonParseException, IOException {
		// Get timezone options
		ObjectMapper objectMapper = new ObjectMapper();

		byte[] jsonByte = Files.readAllBytes(Paths.get("/timeZoneList.json"));
		String jsonString = new String(jsonByte, Charset.forName("UTF-8"));

		List timeZonelist = objectMapper.readValue(jsonString, objectMapper.getTypeFactory()
				.constructCollectionType(List.class, TimeZone.class));

		// Use org.joda.time to get user current timezone
		String currentTimeZone = "";
		DateTime dateTime = DateTime.now(DateTimeZone.getDefault());
		for (TimeZone timezone : timeZonelist) {
			if (timezone.getZoneID().startsWith(String.valueOf(dateTime.getZone())))
				currentTimeZone = timezone.getZoneName();

		return Response.status(200).entity(currentTimeZone).build();
(Visited 100 time, 1 visit today)
Comments are closed.