如何解析.net DateTime作为json字符串接收到java的Date对象中 [英] How to parse .net DateTime received as json string into java's Date object
问题描述
我通过我的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屋!