GSON默认日期序列化程序是特定于语言环境的

问题描述 投票:0回答:2

[在我的Java应用程序中,我使用的是REST API,它以JSON格式返回数据,并且注意到此特定的API以一种特殊的方式格式化了它的日期:“ Nov 1,2019”,但是问题是服务器上的实际日期是“ 2019-11-02”。这意味着我将获取日期最小化为以前的日期。我的服务器在另一个国家。下面是完整的json我格式化后得到。

jsonAccts [{"id":8,"userId":2,"departmentId":45,"effectiveFrom":"Jun 9, 2019","endsOn":"Nov 1, 2019","createdBy":2,"createdOn":"2019-11-02 05:34:11"}]

在所有日期字段上都存在此问题。我该如何解决。我需要在REST API请求上在数据库上获得相同的日期。下面是我用于gson格式化的代码。

    Gson gson;
    GsonBuilder builder;
    SimpleDateFormat dtf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
    SimpleDateFormat dtfDate=new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
    String jsonAccts = null;
    try{
        builder = new GsonBuilder();
        builder.registerTypeAdapter(Timestamp.class, new JsonSerializer<Timestamp>() {
            @Override
            public JsonElement serialize(Timestamp src, Type typeOfSrc, JsonSerializationContext context) {
                dtf.setTimeZone(TimeZone.getTimeZone("UTC"));
                String jsDate = dtf.format(src);
                return new JsonPrimitive(jsDate);
            }
        });
        gson = builder.create();
        List<ClassTeacher> allActPgmMap = new ArrayList<ClassTeacher>();
        allActPgmMap = springDao.getClassTeacherList(Integer.parseInt(deptId));
        Type listType = new TypeToken<List<ClassTeacher>>() {}.getType();
        jsonAccts = gson.toJson(allActPgmMap, listType);
    }catch(Exception e){
        e.printStackTrace();
    }
    return jsonAccts;

下面是ClassTeacher类。

import javax.persistence.*;
    import java.io.Serializable;
    import java.sql.Timestamp;
    import java.util.Date;

    @Entity
    @Table(name = "class_teacher")
    public class ClassTeacher implements Serializable,Comparable {

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "id")
        private long id;

        @Column(name = "user_id")
        private long userId;

        @Column(name = "department_id")
        private long departmentId;

        @Column(name = "effective_from")
        @Temporal(TemporalType.DATE)     
        private Date effectiveFrom;

        @Column(name = "ends_on")
        @Temporal(TemporalType.DATE)     
        private Date endsOn;

        @Column(name="created_by")
        private long createdBy;

        @Column(name="created_on")
        private Timestamp createdOn;

        public ClassTeacher() {

        }

        public ClassTeacher(long id, long departmentId, long userId, Date effectiveFrom, Date endsOn, long createdBy, Timestamp createdOn) {
            this.id = id;
            this.departmentId = departmentId;
            this.userId = userId;
            this.effectiveFrom = effectiveFrom;
            this.endsOn = endsOn;
            this.createdBy = createdBy;
            this.createdOn = createdOn;
        }

        public long getId() {
            return id;
        }

        public void setId(long id) {
            this.id = id;
        }

        public long getUserId() {
            return userId;
        }

        public void setUserId(long userId) {
            this.userId = userId;
        }

        public long getDepartmentId() {
            return departmentId;
        }

        public void setDepartmentId(long departmentId) {
            this.departmentId = departmentId;
        }

        public Date getEffectiveFrom() {
            return effectiveFrom;
        }

        public void setEffectiveFrom(Date effectiveFrom) {
            this.effectiveFrom = effectiveFrom;
        }

        public Date getEndsOn() {
            return endsOn;
        }

        public void setEndsOn(Date endsOn) {
            this.endsOn = endsOn;
        }

        public long getCreatedBy() {
            return createdBy;
        }

        public void setCreatedBy(long createdBy) {
            this.createdBy = createdBy;
        }

        public Timestamp getCreatedOn() {
            return createdOn;
        }

        public void setCreatedOn(Timestamp createdOn) {
            this.createdOn = createdOn;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            ClassTeacher that = (ClassTeacher) o;

            if (id != that.id) return false;
            if (createdBy != that.createdBy) return false;
            if (userId != null ? !userId.equals(that.userId) : that.userId != null) return false;
            if (departmentId != null ? !departmentId.equals(that.departmentId) : that.departmentId != null) return false;
            if (effectiveFrom != null ? !effectiveFrom.equals(that.effectiveFrom) : that.effectiveFrom != null)
                return false;
            if (endsOn != null ? !endsOn.equals(that.endsOn) : that.endsOn != null) return false;
            if (createdOn != null ? !createdOn.equals(that.createdOn) : that.createdOn != null) return false;
        }

        @Override
        public int hashCode() {
            int result = (int) (id ^ (id >>> 32));
            result = 31 * result + (userId != null ? userId.hashCode() : 0);
            result = 31 * result + (departmentId != null ? departmentId.hashCode() : 0);
            result = 31 * result + (effectiveFrom != null ? effectiveFrom.hashCode() : 0);
            result = 31 * result + (endsOn != null ? endsOn.hashCode() : 0);
            result = 31 * result + (int) (createdBy ^ (createdBy >>> 32));
            result = 31 * result + (createdOn != null ? createdOn.hashCode() : 0);
            return result;
        }

        @Override
        public int compareTo(Object comparestu) {
            return this.getEffectiveFrom().compareTo(((ClassTeacher)comparestu).getEffectiveFrom());
        }
    }
java json date gson utc
2个回答
0
投票

问题是服务器返回的日期为“ Nov 1,2019”。在这种格式下,您没有时间和时区,因此无法正确格式化日期。如果您无法更改服务器端,则看不到任何解决方案,否则解决方案很少:


0
投票

您的问题甚至比这更深。在不包括时区偏移量的情况下格式化任何类型的日期或时间对象总是很含糊。这个时间点:

© www.soinside.com 2019 - 2024. All rights reserved.