日期字段在MS WCF兼容格式GSON系列化 [英] gson serialization of Date field in MS WCF compatible form

查看:181
本文介绍了日期字段在MS WCF兼容格式GSON系列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我访问POST方法的Web服务。我需要发送到服务器的JSON序列化对象。在我的Andr​​oid类我有一些字符串字段和日期字段。该日期字段被序列化是这样的:

I access a web service in a POST method. I need to send to the server a json serialized object. In my Android class I have some string fields and a Date field. This Date field gets serialized like this:

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

但为了与Web服务兼容,我需要有它这样的:

but to be compatible with the web service I need to have it like:

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

我发现有关反序列化在这里一个有趣的文章: HTTP ://benjii.me/2010/04/deserializing-json-in-android-using-gson/ 我想我需要做这样的事情。你能给我一个伸出援助之手?

I found an interesting article about Deserialization in here: http://benjii.me/2010/04/deserializing-json-in-android-using-gson/ I think I need to do something like this. Could you give me a helping hand ?

推荐答案

在任何情况下需要它,这里是我做到了。 1.创建一个新的类DateSerializer,并把它:

In case anybody needs it, here is how I did it. 1. Create a new class DateSerializer and put in it:

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() + ")/");
    }
}

这里是我如何使用它:

And here is how I use it:

   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;
}

这篇关于日期字段在MS WCF兼容格式GSON系列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆