Error "gson.JsonSyntaxException" when I try to retrieve a document with a date in MongoDB
I receive from server a Json Object with a long value (Timestamp) for Date.
I am creating my Gson object:
final Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDateDeserializer()).create();
This is code for my JsonDateDeserializer:
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
import java.util.Date;
public class JsonDateDeserializer implements JsonDeserializer<Date> {
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
long time = json.getAsJsonPrimitive().getAsLong();
Date d = new Date(time);
return d;
}
}
Updated long time = json.getAsJsonObject().getAsJsonPrimitive("$date").getAsLong();
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
import java.util.Date;
public class JsonDateDeserializer implements JsonDeserializer<Date> {
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
long time = json.getAsJsonObject().getAsJsonPrimitive("$date").getAsLong();
Date d = new Date(time);
return d;
}
}
http://www.techiesinfo.com/performance