Skip to content Skip to sidebar Skip to footer

Parsing Object Containing Date Using Gson - Unparseable Date

I have the following JSON data - [ { 'Name': 'Litware, Inc. (sample)', '__type': 'CRMService.Account', 'Status': 0, 'Owner': 'abijeet patro',

Solution 1:

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.

publicclassCustomDeserializerimplementsJsonDeserializer<CRMActivity> {

    publicCRMActivitydeserialize(JsonElement json, Type typeOfT,
            JsonDeserializationContext context) throws JsonParseException {

        if (json == null)
            returnnull;

        JsonObject jo = json.getAsJsonObject();

        Stringtype = 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(")/", "");

        returnnewCRMActivity(type, newDate(Long.valueOf(startTimeAsString)),
                newDate(Long.valueOf(endTimeAsString)), subject);

    }

and call it this way:

publicclassQ19657666 {

    /**
     * @param args
     */publicstatic 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]

Post a Comment for "Parsing Object Containing Date Using Gson - Unparseable Date"