2017-12-01 5 views
2

私は3つのタイムスタンプフィールドを持つオブジェクトがあり、私はGsonを使用してjson応答を消費したいが、私は無効なタイムゾーンインジケータを持っている。 これはアウトプットです:Gsonを使用してタイムスタンプを持つJsonの応答を処理するにはどうすればよいですか? java.lang.IndexOutOfBoundsException

com.google.gson.JsonSyntaxException: 2017-11-30 15:19:37 
at com.google.gson.DefaultDateTypeAdapter.deserialize(DefaultDateTypeAdapter.java:84) 

... 31 more Caused by: java.lang.IndexOutOfBoundsException: Invalid time zone indicator ' ' 
at com.google.gson.internal.bind.util.ISO8601Utils.parse(ISO8601Utils.java:245) 
... 32 more 
Caused by: java.lang.IndexOutOfBoundsException: Invalid time zone indicator ' ' 
at com.google.gson.internal.bind.util.ISO8601Utils.parse(ISO8601Utils.java:245) 
... 32 more 

そして、これは私のJSONレスポンスです:

{ 
"status": "OK", 
"data": { 
    "due_days": 10, 

    "attested_at": null, 
    "updated_at": "2017-12-01 11:59:56", 
    "automatic_collection": { 
     "amount": null, 
     "delay_days": null 
    }, 
    "currency": "SEK", 
     "collector_paid_sum": 0, 
     "remaining_sum": 0 
    }, 
    "id": "zeY37WJ", 
    "reminder_fee": 60.0, 
    "interest_rate": 8.5, 
    "state": "Unattested", 
    "due_date": "2017-12-11", 
    "automatic_reminders_settings": [], 
    "invoice_fee_vat": 0, 
    "invoice_date": "2017-12-01", 
    "reminder_count": 0, 
    "interest_fee": 0.0, 
    "invoice_no": 0, 
    "created_at": "2017-11-30 15:21:08", 
    "total_sum": 0.0, 
    "delivery_method": "Letter", 
    "remaining_sum": 0.0, 
    "flags": [], 
} 

}

この私のGsonコード:

GsonBuilder gsonBuilder = new GsonBuilder(); 
    Gson gson = gsonBuilder.registerTypeAdapter(Timestamp.class, new DateDeserializer()).create(); 
    invoiceModels = gson.fromJson(jsonObject.get("data").toString(), InvoiceModel[].class); 

と、これは私のDateDeserializerです

public class DateDeserializer implements JsonDeserializer<Date> { 
public Date deserialize(JsonElement element, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { 
    String date = element.getAsString(); 

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ'"); 
    format.setTimeZone(TimeZone.getTimeZone("GMT")); 

    try { 
     return format.parse(date); 
    } catch (ParseException exp) { 
     System.out.println("Failed to parse Date:"+ exp); 
     return null; 
    }}} 

答えて

0

にタイムゾーンパターンのフラグメントZを明示的に含めるようです。あなたのデータはタイムゾーンを含んでおらず、あなたの例から判断してください。

フォーマッタでタイムゾーンを設定しても、解析された文字列のタイムゾーン部分は無視されません。代わりに、タイムゾーンデータがない場合に使用されます。

-1
GsonBuilder gsonBuilder = new GsonBuilder(); 
Gson gson = gsonBuilder.registerTypeAdapter(Timestamp.class, new DateDeserializer()). **.setDateFormat(DateFormatUtils.ISO_DATETIME_FORMAT.getPattern())** 
create(); 

に動作します
関連する問題