我接受这个String并将其解析为Javascript对象。
{
"startTime": 233432420233,
"endTime": 233432431000,
"bufferingDelays": [
{
"time": 233432420233,
"delayLength": 100
},
{
"time": 233432420433,
"delayLength": 50
},
{
"time": 233432420833,
"delayLength": 75
}
]
}
以下是进行解析的Javascript代码,然后转换为JSON字符串:
var reportObject = jQuery.parseJSON(reportJSONString);
reportObject.startTime = new Date(reportObject.startTime);
reportObject.endTime = new Date(reportObject.endTime);
for (var i = 0; i < reportObject.bufferingDelays.length; i++)
{
var delay = reportObject.bufferingDelays[i];
delay.time = new Date( delay.time );
reportObject.bufferingDelays[i] = delay;
}
var reportObjectFinalString = JSON.stringify( reportObject );
JSON转换产生的日期之一是:1977-05-25T18:20:20.233Z
。我认为尾随'Z'是坏的。
现在在Java中我尝试将其解析为Java对象,如下所示:
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").create();
Report report = gson.fromJson( jsonBuilder.toString(), Report.class );
但我得到了这个例外:
SEVERE: Servlet.service() for servlet [ReportServlet] in context with path [/Report] threw exception [com.google.gson.JsonSyntaxException: 1977-05-25T18:20:20.233Z] with root cause
java.text.ParseException: Unparseable date: "1977-05-25T18:20:20.233Z"
答案 0 :(得分:10)
您还需要引用Z
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create();
SimpleDateFormat
(在GsonBuilder
中使用)将不带引号的Z
表示您的日期字符串所没有的时区。