2010-10-06 39 views
2

我使用POST方法訪問Web服務。我需要向服務器發送一個json序列化對象。在我的Android類中,我有一些字符串字段和一個日期字段。該日期字段被序列化這樣的:gson序列化MS WCF兼容表格中的日期字段

.... TouchDateTime":"Oct 6, 2010 5:55:29 PM"}" 

,但要與Web服務兼容,我需要有它喜歡:

"TouchDateTime":"\/Date(928138800000+0300)\/" 

我發現了大約反序列化的有趣的文章在這裏:http://benjii.me/2010/04/deserializing-json-in-android-using-gson/我認爲我需要做這樣的事情。你能幫我一把嗎?

+0

此外,你可以在這裏看到:http://stackoverflow.com/questions/206384/how-to-format-a-json-date – Cody 2011-12-28 18:36:44

+0

我用http://stackoverflow.com/a/ 2453820/8524獲取上述的TimeZone偏移量。你是怎麼做到的? – Diederik 2012-05-30 14:55:48

回答

8

如果有人需要它,這裏是我是如何做到的。 1.創建一個新的類DateSerializer,並把它:

import java.lang.reflect.Type; 
import java.util.Date; 
import com.google.gson.JsonElement; 
import com.google.gson.JsonPrimitive; 
import com.google.gson.JsonSerializationContext; 
import com.google.gson.JsonSerializer; 

public class DateSerializer implements JsonSerializer<Object> 
{ 
    public JsonElement serialize(Date date, Type typeOfT, JsonSerializationContext context) 
    { 
     return new JsonPrimitive("/Date(" + date.getTime() + ")/"); 
    } 

    public JsonElement serialize(Object arg0, Type arg1, 
      JsonSerializationContext arg2) { 

     Date date = (Date) arg0; 
     return new JsonPrimitive("/Date(" + date.getTime() + ")/"); 
    } 
} 

這裏是我如何使用它:

public static JSONObject Object(Object o){ 
    try { 
     GsonBuilder gsonb = new GsonBuilder(); 
     DateSerializer ds = new DateSerializer(); 
     gsonb.registerTypeAdapter(Date.class, ds); 
     Gson gson = gsonb.create(); 


     return new JSONObject(gson.toJson(o)); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    return null; 
} 
+0

我可以問爲什麼添加「日期()」和/字符?我已經在衆多的例子中看到了它,但我無法將它包裹起來。爲什麼不把毫秒數作爲一個數字?謝謝 – JayPea 2011-11-14 21:26:05

+0

@JayPea,因爲這是延遲的WCF .NET DateTime格式的一部分。如果您以JSON的形式看到它,那麼API可能也會以其他方式出現異常遲緩。 – straya 2015-08-05 01:12:02