Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中将JSON对象转换为util.Date_Java_Android_Json_Date_Time - Fatal编程技术网

在Java中将JSON对象转换为util.Date

在Java中将JSON对象转换为util.Date,java,android,json,date,time,Java,Android,Json,Date,Time,我有一个像这样的对象: { "date": 12, "day": 3, "hours": 12, "minutes": 32, "month": 8, "seconds": 32, "time": 1536755552909, "timezoneOffset": 0, "year": 118 } 我以前使用util.Date来生成日期,但现在我从Node.js服务器获得上面的格式。如何将其转换为日期类型 当我试着去做 St

我有一个像这样的对象:

{
    "date": 12,
    "day": 3,
    "hours": 12,
    "minutes": 32,
    "month": 8,
    "seconds": 32,
    "time": 1536755552909,
    "timezoneOffset": 0,
    "year": 118
}
我以前使用
util.Date
来生成日期,但现在我从Node.js服务器获得上面的格式。如何将其转换为
日期
类型

当我试着去做

StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            JsonParser jsonParser = new JsonParser();
            JsonElement jsonElement = jsonParser.parse(response);
            Gson gson = new Gson();
            Date date = gson.fromJson(jsonElement,Date.class);

            lastLoadedDate = date;

            elapsedTime = 0;

        }
    }
StringRequest-StringRequest=new-StringRequest(Request.Method.GET,url,new-Response.Listener()){
@凌驾
公共void onResponse(字符串响应){
JsonParser JsonParser=新的JsonParser();
JsonElement=jsonParser.parse(响应);
Gson Gson=新的Gson();
Date-Date=gson.fromJson(jsonElement,Date.class);
lastLoadedDate=日期;
elapsedTime=0;
}
}
这会失败,因为它不是一个字符串,节点服务器会发送一个JSON。如果我执行了
new Response.Listener()
,因为它是一个JSON,而不是一个日期。像这样将JSON转换为Date
Date now=(Date)myJsonResponse
会导致Android Studio错误地说:

无法争辩的类型:无法将JSONObject强制转换为最新


Edit.I不能使用util.Date,因为我需要来自服务器的时间,以便对每个人都通用。

如果可能的话,让服务器以更好的格式返回日期,因为这样可以避免歧义并减少JSON负载


如果不可能,您必须决定使用JSON的哪些部分,或者是
time
,或者是不同的值,比如
hours
minutes
,…通过手动挑选这些部分,您可以使用其构造函数之一或者通过
java.util.Calendar
对象手动构建一个
Date
对象ct(因为java 8中不推荐使用
java.util.Date
中的许多构造函数)。

如果您想使用java的util.Date,您可以自己生成它

在中,您可以找到合适的承包商声明,如
日期(整数年、整数月、整数日期、整数小时、整数分钟、整数秒)

因此,您可以从json中创建它,您只需从中获取适当的值(以指定json对象的方式->在我的示例中,它是一个对象):


首先,创建这样一个POJO类

    public class ResponseModel {

    private int date;
    private int day;
    private int hours;
    private int minutes;
    private int month;
    private int seconds;
    private long time;
    private int timezoneOffset;
    private int year;

    public int getDate() {
        return date;
    }

    public ResponseModel setDate(int date) {
        this.date = date;
        return this;
    }

    public int getDay() {
        return day;
    }

    public ResponseModel setDay(int day) {
        this.day = day;
        return this;
    }

    public int getHours() {
        return hours;
    }

    public ResponseModel setHours(int hours) {
        this.hours = hours;
        return this;
    }

    public int getMinutes() {
        return minutes;
    }

    public ResponseModel setMinutes(int minutes) {
        this.minutes = minutes;
        return this;
    }

    public int getMonth() {
        return month;
    }

    public ResponseModel setMonth(int month) {
        this.month = month;
        return this;
    }

    public int getSeconds() {
        return seconds;
    }

    public ResponseModel setSeconds(int seconds) {
        this.seconds = seconds;
        return this;
    }

    public long getTime() {
        return time;
    }

    public ResponseModel setTime(long time) {
        this.time = time;
        return this;
    }

    public int getTimezoneOffset() {
        return timezoneOffset;
    }

    public ResponseModel setTimezoneOffset(int timezoneOffset) {
        this.timezoneOffset = timezoneOffset;
        return this;
    }

    public int getYear() {
        return year;
    }

    public ResponseModel setYear(int year) {
        this.year = year;
        return this;
    }
}
然后像这样将字符串响应转换为
ResponseModel.class

Gson gson = new Gson();
ResponseModel model = gson.fromJson(jsonElement,ResponseModel.class);
然后创建一个如下所示的方法

private Date getDateFromResponse(ResponseModel model) {
        Calendar calendar = Calendar.getInstance();

        //-----
        calendar.set(Calendar.DAY_OF_MONTH, model.getDate());
        calendar.set(Calendar.MONTH, model.getMonth());
        calendar.set(Calendar.YEAR, model.getYear());
        calendar.set(Calendar.HOUR, model.getHours());
        calendar.set(Calendar.MINUTE, model.getMinutes());
        calendar.set(Calendar.SECOND, model.getSeconds());

        //OR
        //You can simply add this line with this time is equal to your all fields
        //And comment all above lines.
        //calendar.setTimeInMillis(model.getTime());

        return calendar.getTime();

    }
只需调用这个方法

Date date = getDateFromResponse(model);

希望这对你有所帮助。

这就是解决问题的方法。谢谢阿尤什·古普塔的评论

StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            try {

                JSONObject jsonObject = new JSONObject(response);

                timestamp = jsonObject.getLong("time");

                lastLoadedDate = new Date(timestamp);

            } catch (JSONException e) {
                //Handle the exception
            }

        }
    }
StringRequest-StringRequest=new-StringRequest(Request.Method.GET,url,new-Response.Listener()){
@凌驾
公共void onResponse(字符串响应){
试一试{
JSONObject JSONObject=新JSONObject(响应);
timestamp=jsonObject.getLong(“时间”);
lastLoadedDate=新日期(时间戳);
}捕获(JSONException e){
//处理异常
}
}
}

我认为
时间
字段代表纪元中的时间,你不能将其转换为日期吗?如果你想获取日期,请使用json——你可以尝试使用字符串格式,如“2018年9月12日3:57:59 PM”@AyushGupta这就是解决问题的方法。你想添加一个答案吗?@AlexIronside我已经有一段时间没有使用JAVA了,所以我对语法不够精通,无法给出一个可接受的答案时间字段可能需要乘以1000才能在安卓系统中工作。可能是真的,还取决于月份是0还是1o正确解释它。这就是为什么我总是坚持ISO-8601以避免所有这些问题。只要插入
time
字段,就可以让Date计算出所有其他内容。只有在不考虑时区的情况下。Date的构造函数中没有Locale参数吗?或者是日历?
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            try {

                JSONObject jsonObject = new JSONObject(response);

                timestamp = jsonObject.getLong("time");

                lastLoadedDate = new Date(timestamp);

            } catch (JSONException e) {
                //Handle the exception
            }

        }
    }