如何将.net DateTime作为json字符串解析为java的Date对象
16lz
2021-01-22
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日期”一章进行操作。
更多相关文章
- 【android】两个view共用同一个animation对象的问题
- 空对象引用错误:使用SQLite的Android Studio
- Android通过反射打造可以存储任何对象的万能SharedPreferences
- android 检测字符串是否为合法域名
- android通知适用于循环中的一个对象[重复]
- android:使用网络通信技术从客户端直接获取服务端的对象数据
- Android 字符串资源
- 领域:更新外部对象的id
- Unity Android使用相机拍摄照片并在其上增加一个3D对象