java - How to convert a Date between Jackson and Gson? -
in our spring-configured rest-server use jackson convert object json. object contains several java.util.date objects.
when attempt deserialize on android device using gson's fromjson method "java.text.parseexception: unparseable date". have tried serializing date timestamp corresponding milliseconds since 1970, same exception.
can gson configured parse timestamp-formatted date such 1291158000000 java.util.date object?
you need register own deserializer dates.
i've created small example below, in json string "23-11-2010 10:00:00" deserialized date object:
import java.lang.reflect.type; import java.text.parseexception; import java.text.simpledateformat; import java.util.date; import com.google.gson.gson; import com.google.gson.gsonbuilder; import com.google.gson.jsondeserializationcontext; import com.google.gson.jsondeserializer; import com.google.gson.jsonelement; import com.google.gson.jsonparseexception; public class dummy { private date date; /** * @param date date set */ public void setdate(date date) { this.date = date; } /** * @return date */ public date getdate() { return date; } public static void main(string[] args) { gsonbuilder builder = new gsonbuilder(); builder.registertypeadapter(date.class, new jsondeserializer<date>() { @override public date deserialize(jsonelement json, type typeoft, jsondeserializationcontext context) throws jsonparseexception { simpledateformat format = new simpledateformat("dd-mm-yyyy hh:mm:ss"); string date = json.getasjsonprimitive().getasstring(); try { return format.parse(date); } catch (parseexception e) { throw new runtimeexception(e); } } }); gson gson = builder.create(); string s = "{\"date\":\"23-11-2010 10:00:00\"}"; dummy d = gson.fromjson(s, dummy.class); system.out.println(d.getdate()); } }
Comments
Post a Comment