java-当字段名称以点开头时,将Json转换为Object

我正在尝试使用Gson从JsonElement转换为Object.
问题是JsonObject有两个名称以点开头的字段,而当我使用gson.fromJson方法时,这些字段未映射.

这是Json对象(令牌对象):

{
   "access_token":"boQtj0SCGz2GFGz[...]",
   "token_type":"bearer",
   "expires_in":1209599,
   "userName":"gonzalo",
   ".issued":"Mon, 14 Oct 2014 06:53:32 GMT",
   ".expires":"Mon, 28 Oct 2014 06:53:32 GMT"
}

这是目标类:

private class BearerToken{
        public String access_token;
        public String token_type;
        public String expires_in;
        public String userName;
        public Date issued;
        public Date expires;

        public BearerToken(){
        }
    }

这是我的代码和结果:

 HttpResponse resp = httpClient.execute(post); // request to server
 String respStr = EntityUtils.toString(resp.getEntity()); // json token
 JsonParser parser = new JsonParser();
 sonElement jsonElement =  parser.parse(respStr);
 BearerToken token = new BearerToken();             
 Gson gson = new Gson();
 token = gson.fromJson(jsonElement, token.getClass());

respStr:

{"access_token":"d7NDuC7accTA[....]",
"token_type":"bearer",
"expires_in":1209599,
"userName":"43344",
".issued":"Tue, 30 Sep 2014 16:03:17 GMT",
".expires":"Tue, 14 Oct 2014 16:03:17 GMT"}

令牌:

字段.expires和.issued始终为null

有什么想法吗?
谢谢.

解决方法:

在适当的字段上设置适当的@SerializedName之后

@SerializedName(".expires")
public Date expires;

您的问题是Gson不知道如何将JSON日期字符串反序列化为Date对象.

您必须添加适当的日期格式.

GsonBuilder builder = new GsonBuilder();
builder.setDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");     
Gson gson = builder.create();
上一篇:工具-----用Gson的Json字符串


下一篇:java-如何让Gson反序列化接口类型?