27

我必须将 Json 对象与具有 Date 的 java 对象绑定。我的 Json 上的日期格式如下:

2013-01-04T10:50:26+0000

我正在使用 GsonBulder 如下:

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create();

但我得到以下异常:

The RuntimeException could not be mapped to a response, re-throwing to the HTTP container
com.google.gson.JsonSyntaxException: 2013-01-04T10:50:26+0000
at com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate(DateTypeAdapter.java:81)
.....
Caused by: java.text.ParseException: Unparseable date: "2013-01-04T10:50:26+0000"
at java.text.DateFormat.parse(DateFormat.java:337)
at com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate(DateTypeAdapter.java:79)

我正在尝试使用 Gson 加载此请求:

https://graph.facebook.com/me?fields=id,username,email,link,updated_time&access_token=accessToken

回应是

{"id":"12345","username":"myusername","email":"myemail\u0040yahoo.it","link":"http:\/\/www.facebook.com\/mysusername","updated_time":"2013-01-04T10:50:26+0000"}
4

2 回答 2

52

反序列化失败,因为 json 字符串中的引号丢失。

以下作品:

    Gson gson=  new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create();

    String date = "\"2013-02-10T13:45:30+0100\"";
    Date test = gson.fromJson(date, Date.class);
    System.out.println("date:" + test);

输出:

日期:2013 年 2 月 10 日星期日 13:45:30 CET

高温高压

编辑完整示例:

import java.util.Date;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;


public class FacebookResponse {

int id;
String username;
String email;
String link;
Date updated_time;

@Override
public String toString() {
    return "ID: " + id + " username: " + username + " email: " + email + " link: " + link + " updated_time: " + updated_time;
};



/**
 * @param args
 */
public static void main(String[] args) {        
    String json = "{\"id\":\"12345\",\"username\":\"myusername\",\"email\":\"myemail\u0040yahoo.it\",\"link\":\"http://www.facebook.com/mysusername\",\"updated_time\":\"2013-01-04T10:50:26+0000\"}";
    Gson gson=  new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create();

    FacebookResponse response = gson.fromJson(json, FacebookResponse.class);
    System.out.println(response);
}

}

于 2013-02-10T12:49:34.560 回答
-1
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response put(@HeaderParam
                    final String userFromString,
                    @Context final HttpServletRequest req) {

    JSONObject jsonObject = new JSONObject(userFromString);
    ReturnCode resultCode = null;
    UserDto user= new UserDto();
    Gson gson=  new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
    user= gson.fromJson(userFromString,UserDto.class);
于 2020-03-24T17:44:37.403 回答