如何解析.net DateTime作为json字符串接收到java的Date对象中 [英] How to parse .net DateTime received as json string into java's Date object

查看:224
本文介绍了如何解析.net DateTime作为json字符串接收到java的Date对象中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过我的asmx webservice接收.NET的 DateTime 对象作为json字符串,并尝试在gson库的帮助下解析它。但似乎没有支持解析.net风格的DateTime。
如何使用Gson轻松地解析为java的 Date 对象,而不用麻烦?

I'm receiving .NET's DateTime object as json string through my asmx webservice and trying to parse it with help of gson library. But seems like there's no support to parse .net style DateTime. How can i parse it easily into java's Date object using Gson without much hassle?

字符串我收到的是:

"DateOfBirth":"\/Date(736032869080)\/"

PS我不想在服务器端进行任何修改以接收DateTime作为Long值

P.S. I would not like to make any modifications at server side to receive DateTime as a Long value

推荐答案

像这样:

String json = "\"\\/Date(736032869080)\\/\"";
Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new NetDateTimeAdapter()).create();
System.out.println("Date=" + gson.fromJson(json, Date.class));

class NetDateTimeAdapter extends TypeAdapter<Date> {
    @Override
    public Date read(JsonReader reader) throws IOException {
        if (reader.peek() == JsonToken.NULL) {
            reader.nextNull();
            return null;
        }
        Date result = null;
        String str = reader.nextString();
        str = str.replaceAll("[^0-9]", "");
        if (!TextUtils.isEmpty(str)) {
            try {
                result = new Date(Long.parseLong(str));
            } catch (NumberFormatException e) {
            }
        }
        return result;
    }
    @Override
    public void write(JsonWriter writer, Date value) throws IOException {
        // Nah..
    }
}

或使用这个例子而不是请参阅处理WCF Microsoft JSON日期一章。

Or use this example instead & follow the "Dealing with WCF Microsoft JSON Dates" chapter.

这篇关于如何解析.net DateTime作为json字符串接收到java的Date对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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