2010-12-01 3 views
5

SpringのRESTサーバーでは、Jacksonを使用してオブジェクトをJsonに変換します。このオブジェクトには、いくつかのjava.util.Dateオブジェクトが含まれています。JacksonとGsonの間で日付を変換するには?

GsonのfromJsonメソッドを使用してAndroidデバイスでデシリアライズしようとすると、「java.text.ParseException:Unparseable date」が表示されます。私たちは、1970年以降のミリ秒に対応するタイムスタンプに日付をシリアル化しようとしましたが、同じ例外が発生します。

1291158000000などのタイムスタンプ形式の日付をjava.util.Dateオブジェクトに解析するようにGsonを設定できますか?

答えて

6

日付用に独自のデシリアライザを登録する必要があります。

私は以下の小さな例を作成しました、でJSON文字列「23-11-2010 10時00分00秒は、」Dateオブジェクトにデシリアライズされる:ジャクソンに関して

import java.lang.reflect.Type; 
import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.Date; 

import com.google.gson.Gson; 
import com.google.gson.GsonBuilder; 
import com.google.gson.JsonDeserializationContext; 
import com.google.gson.JsonDeserializer; 
import com.google.gson.JsonElement; 
import com.google.gson.JsonParseException; 


public class Dummy { 
    private Date date; 

    /** 
    * @param date the date to set 
    */ 
    public void setDate(Date date) { 
     this.date = date; 
    } 

    /** 
    * @return the date 
    */ 
    public Date getDate() { 
     return date; 
    } 

    public static void main(String[] args) { 
     GsonBuilder builder = new GsonBuilder(); 
     builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { 

      @Override 
      public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) 
        throws JsonParseException { 

       SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); 
       String date = json.getAsJsonPrimitive().getAsString(); 
       try { 
        return format.parse(date); 
       } catch (ParseException e) { 
        throw new RuntimeException(e); 
       } 
      } 
     }); 
     Gson gson = builder.create(); 
     String s = "{\"date\":\"23-11-2010 10:00:00\"}"; 
     Dummy d = gson.fromJson(s, Dummy.class); 
     System.out.println(d.getDate()); 
    } 
} 
+1

これは本当に質問に答えるものではありませんか?質問には、「タイムスタンプ形式の日付」 – Nilzor

1

、あなたは数値(タイムスタンプ)とテキストシリアル化(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS)のどちらかを選択できるだけでなく、テキストバリアント(SerializationConfig.setDateFormat)に使用する正確なDateFormatも定義できます。したがって、Jacksonが使用するISO-8601フォーマットをサポートしていない場合、Gsonが認識しているものを強制的に使用できるはずです。

また、Gsonを使用しても構わないのであれば、JacksonはAndroidでうまく動作します。

関連する問題