如果有人需要它,這裏是我是如何做到的。 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;
}
此外,你可以在這裏看到:http://stackoverflow.com/questions/206384/how-to-format-a-json-date – Cody 2011-12-28 18:36:44
我用http://stackoverflow.com/a/ 2453820/8524獲取上述的TimeZone偏移量。你是怎麼做到的? – Diederik 2012-05-30 14:55:48