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?
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
解决方案
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 {
@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.