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?

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

the string i receive is like:

我收到的字符串如下:

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

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

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

5 个解决方案

#1


11

Like this:

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

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

或者使用此示例,并按照“处理WCF Microsoft JSON日期”一章进行操作。

更多相关文章

  1. 【android】两个view共用同一个animation对象的问题
  2. 空对象引用错误:使用SQLite的Android Studio
  3. Android通过反射打造可以存储任何对象的万能SharedPreferences
  4. android 检测字符串是否为合法域名
  5. android通知适用于循环中的一个对象[重复]
  6. android:使用网络通信技术从客户端直接获取服务端的对象数据
  7. Android 字符串资源
  8. 领域:更新外部对象的id
  9. Unity Android使用相机拍摄照片并在其上增加一个3D对象

随机推荐

  1. android 随手记-画虚线
  2. Android 允许权限
  3. android中文字跑马灯效果
  4. Android日期时间格式国际化
  5. android 颜色值 xml
  6. Android Property System
  7. 【Android UI】色板
  8. AndroidщАЪш┐ЗViewPagerхоЮчО
  9. 在eclipse中查看Android(安卓)SDK源代码
  10. 2013.10.14 “?android ”