Snake
Snake

Reputation: 14668

Deserialize json using GSON for timestamps

I have a json string such as

{"start_time": "10:00 AM", "end_time" : "11:00 PM"}

If I use the POJO deserializtion using GSON then as you can see these will be mapped to String variables in my class. Ultimately, I want to use take a time provided by user and see if it is within the range. The only way I can think of is that every time I get a time, then I would convert these string vairables to object(whether it is Joda time, Date, LocalTime ..etc) and then do the comparison.

Is there a better way? Can I have GSON deserialize the string directly to a time object? Or somehow save the step of always doing these conversion during comparison? Or the way I am proposing really the correct design ?

Thank you

Upvotes: 0

Views: 3942

Answers (4)

MeetTitan
MeetTitan

Reputation: 3568

You're not asking much of a library. You could write the class yourself in pure java since you're only comparing 24 hours of a day. You could so something like:

public class TimeKeeper implements Comparable<TimeKeeper> {
    byte startHour;
    byte startMinute;
    byte endHour;
    byte endMinute;
    public TimeKeeper(String start, String end) {
        startHour = parseHour(start);
        startMinute = parseMinute(start);
        endHour = parseHour(end);
        endMinute = parseMinute(end);
    }
    public byte parseHour(String time) {
        byte hour = Byte.valueOf(String.split(time, ":")[0]);
        if(time.contains("PM") {
            hour += 12;
        }
        return hour;
    }
    public byte parseMinute(String time) {
         return Byte.valueOf(String.valueOf(time, ":")[1].substring(0, 2));
    }
    @Override
    public int compareTo(TimeKeeper tk) {
        int diff = startHour - tk.startHour;
        if(diff == 0) {
            return startMinute - tk.startMinute;
        }
        return diff;
    }
}

Upvotes: 0

S.K.
S.K.

Reputation: 3677

You can use GsonBuilder to parse the times into Dates, specifying the date format:

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setDateFormat("HH:mm a");
    Gson gson = gsonBuilder.create();
    Pojo fromJson = gson.fromJson(<string>, Pojo.class);

The POJO fields will look like (rename if you need to):

    private Date start_time;
    private Date end_time;

Upvotes: 1

Nawnit Sen
Nawnit Sen

Reputation: 1038

I couldn't do it using Gson but using jackson library it is possible.For that you will have to make some modification in setter method of your POJO. Add the following jackson dependency in your pom and then make modification in your POJO as per below example. In my POJO in setter method i am taking string as input parameter and assign it after converting it to date.

Dependency:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.7</version>
</dependency>

POJO class : Here i have not added null check in setter which can lead to NPE if there are no value corresponding to start and end date in json. So you can add a null check in setter before converting it to Date.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

class TimePojo {
    private Date start_time;
    private Date end_time;
    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");

    public Date getStart_time() {
        return start_time;
    }

    public void setStart_time(String start_time) throws ParseException {

        this.start_time = sdf.parse(start_time);
    }

    public Date getEnd_time() {
        return end_time;
    }

    public void setEnd_time(String end_time) throws ParseException {
        this.end_time = sdf.parse(end_time);
    }

}

And the code to convert json to POJO using jackson

import java.io.IOException;

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

public class TestGson {
    public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
        String json = "{\"start_time\": \"10:00 AM\", \"end_time\" : \"11:00 PM\"}";
        ObjectMapper mapper = new ObjectMapper();
        TimePojo obj = mapper.readValue(json, TimePojo.class);
        System.out.println(obj.getStart_time());
        System.out.println(obj.getEnd_time());
    }
}

Upvotes: 0

JuanKman94
JuanKman94

Reputation: 112

Have you written a class with those two properties specifying an Hour-like (maybe Calendar) type? E.g.:

public MyTimeRange {
  private Calendar startTime;
  private Calendar endTime;
  ...
}

And then, when deserializing:

MyTimeRange myRange = gson.fromJson(jsonStr, MyTimeRange.class);

Upvotes: 0

Related Questions