【问题标题】:gson serialization of Date field in MS WCF compatible formMS WCF 兼容形式的日期字段的 gson 序列化
【发布时间】:2011-04-21 21:53:12
【问题描述】:

我以 POST 方法访问 Web 服务。我需要向服务器发送一个 json 序列化对象。在我的 Android 类中,我有一些字符串字段和一个日期字段。这个日期字段的序列化如下:

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

但要与网络服务兼容,我需要像这样:

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

我在这里找到了一篇关于反序列化的有趣文章:http://benjii.me/2010/04/deserializing-json-in-android-using-gson/ 我想我需要做这样的事情。你能帮帮我吗?

【问题讨论】:

标签: android serialization gson


【解决方案1】:

如果有人需要,我就是这样做的。 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;
}

【讨论】:

  • 我能问一下为什么要添加“Date()”和 / 字符吗?我已经在很多例子中看到了它,但我就是无法理解它。为什么不将毫秒作为数字传输?谢谢
  • @JayPea 因为这是延迟的 WCF .NET DateTime 格式的一部分。如果您在 JSON 中看到它,很可能该 API 在其他方面也异常迟钝。
【解决方案2】:

如果有人需要序列化和反序列化,我已经为它准备了一个 GsonHelper: How to parse .net DateTime received as json string into java's Date object

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    • 2012-10-13
    • 2017-04-16
    • 1970-01-01
    • 1970-01-01
    • 2013-02-05
    相关资源
    最近更新 更多