Android: How to deserialize this format of Date using GSON?
Try this:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return new Date(json.getAsJsonPrimitive().getAsLong());
}
});
Gson gson = builder.create();
Gson - unparseable date error?
base on this post you just register an adapter for Date :
Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return new Date(json.getAsJsonPrimitive().getAsLong());
}
}).create();
ScheduledPeriod scheduledPeriod = gson.fromJson(jsonRequest, ScheduledPeriod.class);
Parsing object containing date using GSON - Unparseable date
I would use a custom deserializer, due to the problem that you have with date parsing, and also since you class has not a parameterless constructor. I limited my example only to the CRMActivity
class.
public class CustomDeserializer implements JsonDeserializer<CRMActivity> {
public CRMActivity deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
if (json == null)
return null;
JsonObject jo = json.getAsJsonObject();
String type = jo.get("Type").getAsString();
String subject = jo.get("Subject").getAsString();
String endTimeAsString = jo.get("EndTime").getAsString();
String startTimeAsString = jo.get("StartTime").getAsString();
startTimeAsString = startTimeAsString.replace("/Date(", "").replace(")/", "");
endTimeAsString = endTimeAsString.replace("/Date(", "").replace(")/", "");
return new CRMActivity(type, new Date(Long.valueOf(startTimeAsString)),
new Date(Long.valueOf(endTimeAsString)), subject);
}
and call it this way:
public class Q19657666 {
/**
* @param args
*/
public static void main(String[] args) {
GsonBuilder gb = new GsonBuilder();
gb.registerTypeAdapter(CRMActivity.class, new CustomDeserializer());
Gson g = gb.create();
String json = "{\"__type\": \"CRMService.Activity\","+
"\"Subject\": \"Call back to understand the problem (sample)\", "+
"\"Type\": \"Phone Call\", "+
"\"RegardingObjectType\": \"account\","+
"\"RegardingObjectId\": \"f3259a52-672f-e311-a7d8-d89d6765b134\","+
"\"EndTime\": \"/Date(1381226400000)/\","+
"\"Id\": \"50b79458-672f-e311-a7d8-d89d6765b134\","+
"\"StartTime\": \"/Date(1381226400000)/\"}";
CRMActivity crmActivity = g.fromJson(json, CRMActivity.class);
System.out.println(crmActivity);
}
}
You'll get this result:
CRMActivity [Type=Phone Call, Subject=Call back to understand the
problem (sample), RegardingObjectType=account, StartTime=Tue Oct 08
12:00:00 CEST 2013, EndTime=Tue Oct 08 12:00:00 CEST 2013]
fromJson raises unparseable date exception
I changed the registerTypeAdapter to be java.util.date and now it works:
SqlDateTypeAdapter sqlAdapter = new SqlDateTypeAdapter();
Gson gson = new GsonBuilder()
.registerTypeAdapter(java.util.Date.class, sqlAdapter )
.setDateFormat("yyyy-MM-dd")
.create();
I am not sure why it works. my type is sql.Date, but this is works..
Gson java.text.ParseException: Unparseable date
You have to define the date Format in the GsonBuilder, something like this.
Gson gSon= new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
Regards!
How to serialize Date to long using gson?
First type adapter does the deserialization and the second one the serialization.
Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (json, typeOfT, context) -> new Date(json.getAsJsonPrimitive().getAsLong()))
.registerTypeAdapter(Date.class, (JsonSerializer<Date>) (date, type, jsonSerializationContext) -> new JsonPrimitive(date.getTime()))
.create();
Usage:
String jsonString = gson.toJson(objectWithDate1);
ClassWithDate objectWithDate2 = gson.fromJson(jsonString, ClassWithDate.class);
assert objectWithDate1.equals(objectWithDate2);
Gson: JsonSyntaxException on date
I found an answer here but I found it strange that there isn't an easier way. Several other json libraries I've used support the .NET json format natively. I was surprised when Gson didn't handle it. There must be a better way. If anyone knows of one, please post it here. All the same, this was my solution:
I created a custom JsonDeserializer and registered it for the Date type. By doing so, Gson will use my deserializer for the Date type instead of its default. The same can be done for any other type if you want to serialize/deserialize it in a custom way.
public class JsonDateDeserializer implements JsonDeserializer<Date> {
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
String s = json.getAsJsonPrimitive().getAsString();
long l = Long.parseLong(s.substring(6, s.length() - 2));
Date d = new Date(l);
return d;
}
}
Then, when I am creating my Gson object:
Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDateDeserializer()).create();
Now my gson object will be capable of parsing the .NET date format (millis since 1970).
Related Topics
How to Keep the Spaces at the End And/Or at the Beginning of a String
Adb Install Fails with Install_Failed_Test_Only
Android Oncreate or Onstartcommand for Starting Service
How to Move the Layout Up When the Soft Keyboard Is Shown Android
How to Change Focus Color of Edittext in Android
Phonegap/Cordova Android Development
How to Perform Collection Group Query Using Document Id in Cloud Firestore
How to Synchronise Projects to Github with Android Studio
"Failure Delivering Result " - Onactivityforresult
How to Get Color-Int from Color Resource
How to Add New Column to Android SQLite Database
Android - Custom UI with Custom Attributes
The Import Android.Support.V7 Cannot Be Resolved
Android O - Old Start Foreground Service Still Working