Example usage for com.google.gson GsonBuilder registerTypeAdapter

List of usage examples for com.google.gson GsonBuilder registerTypeAdapter

Introduction

In this page you can find the example usage for com.google.gson GsonBuilder registerTypeAdapter.

Prototype

@SuppressWarnings({ "unchecked", "rawtypes" })
public GsonBuilder registerTypeAdapter(Type type, Object typeAdapter) 

Source Link

Document

Configures Gson for custom serialization or deserialization.

Usage

From source file:com.quix.aia.cn.imo.rest.InterviewRest.java

License:Open Source License

@POST
@Path("/candidateRegister")
@Consumes(MediaType.TEXT_PLAIN)/*w w w .  j  a  v a 2s  .  c om*/
@Produces({ MediaType.APPLICATION_JSON })
public Response candidateRegister(@Context HttpServletRequest request, @Context ServletContext context,
        String jsonString) {
    log.log(Level.INFO, "InterviewRest --> candidateRegister");
    log.log(Level.INFO,
            "InterviewRest --> candidateRegister --> Data for Candidate Registration...  ::::: " + jsonString);
    boolean status = false;
    boolean isDuplicate = false;
    Integer registeredCount = 0;
    MsgBeans beans = new MsgBeans();
    String agentId = request.getParameter("agentId");
    String coBranch = request.getParameter("co");
    AuditTrailMaintenance auditTrailMaint = new AuditTrailMaintenance();
    try {
        AamData aamData = AamDataMaintenance.retrieveDataToModel(agentId, coBranch);
        InterviewAttendanceMaintenance objMaintenance = new InterviewAttendanceMaintenance();
        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
            @Override
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                    throws JsonParseException {
                Date date = LMSUtil.convertDateToyyyymmddhhmmssDashed(json.getAsString());
                if (null != date) {
                    return date;
                } else {
                    return LMSUtil.convertDateToyyyy_mm_dd(json.getAsString());
                }
            }
        });

        Gson googleJson = builder.create();
        Type listType = new TypeToken<List<InterviewCandidate>>() {
        }.getType();
        List<InterviewCandidate> jsonObjList = googleJson.fromJson(jsonString, listType);
        InterviewCandidate candidate = jsonObjList.get(0);
        candidate.setAgentName(aamData.getAgentName());
        candidate.setBuName(aamData.getBu());
        candidate.setDistName(aamData.getDistrict());
        candidate.setCityName(aamData.getCity());
        candidate.setSscName(aamData.getSsc());
        candidate.setAgencyLeaderCode(aamData.getLeaderCode());
        candidate.setInterviewCandidateCode("" + candidate.getCandidateCode());
        candidate.setBuCode(aamData.getBuCode());
        candidate.setDistrictCode(aamData.getDistrictCode());
        candidate.setCityCode(aamData.getCity());
        candidate.setSscCode(aamData.getSsc());
        candidate.setOfficeCode(aamData.getOfficeCode());
        if (candidate.getStatusStr() != null && candidate.getStatusStr().equalsIgnoreCase("true"))
            candidate.setStatus(true);
        else
            candidate.setStatus(false);

        AddressBookMaintenance addrBookMain = new AddressBookMaintenance();
        String nric = addrBookMain.getNric(Integer.parseInt(candidate.getInterviewCandidateCode()));
        candidate.setNric(nric);

        //           candidate.setAgencyLeaderName(aamData.getTeamName());

        if (!objMaintenance.checkDuplicateCandiadteReg("" + candidate.getInterviewCode(),
                candidate.getServicingAgent(), candidate.getInterviewCandidateCode())) {
            objMaintenance.createNewCandidate(candidate, request);
            String emailAddrs = addrBookMain
                    .getEmailAddress(Integer.parseInt(candidate.getInterviewCandidateCode()));
            if (emailAddrs != null && emailAddrs.length() > 0) {
                EmailNotification.sendInterviewRegEmailNotification(candidate, emailAddrs, aamData);
            }

            String conditionFieldName[] = { "addressCode" };
            String conditionFieldValue[] = { candidate.getInterviewCandidateCode() };
            new AddressBookMaintenance().updateAddressBookStatus("2/9", conditionFieldName,
                    conditionFieldValue);

            List<InterviewCandidate> list1 = objMaintenance.getAttendanceList(request,
                    candidate.getInterviewCode());
            registeredCount = list1.size();
            auditTrailMaint.insertAuditTrail(new AuditTrail("Rest", AuditTrail.MODULE_INTERVIEW_REG,
                    AuditTrail.FUNCTION_REST, "SUCCESS"));
            status = true;
        } else {
            auditTrailMaint.insertAuditTrail(
                    new AuditTrail("Rest", AuditTrail.MODULE_INTERVIEW_REG, AuditTrail.FUNCTION_REST, "FAIL"));
            isDuplicate = true;
        }
    } catch (Exception e) {
        log.log(Level.INFO, "InterviewRest --> candidateRegister --> Exception..... ");
        log.log(Level.SEVERE, e.getMessage());
        e.printStackTrace();
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        LogsMaintenance logsMain = new LogsMaintenance();
        logsMain.insertLogs("InterviewRest", Level.SEVERE + "", errors.toString());

        auditTrailMaint.insertAuditTrail(
                new AuditTrail("Rest", AuditTrail.MODULE_INTERVIEW_REG, AuditTrail.FUNCTION_FAIL, "FAILED"));
        beans.setCode("500");
        beans.setMassage("Database Error");
    }

    return Response.status(200).entity("[{\"status\":" + status + ",\"isDuplicate\":" + isDuplicate
            + ",\"registeredCount\":" + registeredCount + "}]").build();
}

From source file:com.quix.aia.cn.imo.rest.TrainingRest.java

License:Open Source License

/**
 * <p>//from w  w  w  . j  a  v a2 s.  c  o m
 * This method inserts Candidate Training Detail record.
 * </p>
 */
//[{"courseCode":"172926","courseName":"38","curriculamCode":"Participation","courseType":"description","startDate":"2015-06-06 08:00:00"}]
@POST
@Path("/pushDetails")
@Consumes(MediaType.TEXT_PLAIN)
@Produces({ MediaType.APPLICATION_JSON })
public Response pushTrainingDetails(@Context HttpServletRequest request, @Context ServletContext context,
        String jsonString) {
    log.log(Level.INFO, " Training --> push Details ");
    log.log(Level.INFO, " Training --> push Details  --> Data ...  ::::: " + jsonString);

    Gson googleJson = null;
    GsonBuilder builder = new GsonBuilder();
    AuditTrailMaintenance auditTrailMaint = new AuditTrailMaintenance();
    CandidateTrainingDetailMaintenance candidateTrainingDetailMaint = new CandidateTrainingDetailMaintenance();
    CandidateTrainingDetail candidateTrainingDetail = null;
    int isSuccessful = 0;

    try {
        log.log(Level.INFO, "Training --> Saving Candidate Training Details ... ");

        builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
            @Override
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                    throws JsonParseException {
                Date date = LMSUtil.convertDateToyyyymmddhhmmssDashed(json.getAsString());
                if (null != date) {
                    return date;
                } else {
                    return LMSUtil.convertDateToyyyy_mm_dd(json.getAsString());
                }
            }
        });

        googleJson = builder.create();
        Type listType = new TypeToken<List<CandidateTrainingDetail>>() {
        }.getType();
        List<CandidateTrainingDetail> jsonObjList = googleJson.fromJson(jsonString, listType);
        candidateTrainingDetail = jsonObjList.get(0);
        candidateTrainingDetail.setCreationDate(new Date());

        candidateTrainingDetailMaint.createNewCandidateTrainingDetail(candidateTrainingDetail, request);

        log.log(Level.INFO, "Training --> Candidate Training Details Saved successfully... ");
        isSuccessful = 1;
    } catch (Exception e) {
        log.log(Level.SEVERE, "Training --> Error in Saving Candidate Training Details.");
        log.log(Level.SEVERE, e.getMessage());
        e.printStackTrace();
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        LogsMaintenance logsMain = new LogsMaintenance();
        logsMain.insertLogs("TrainingRest", Level.SEVERE + "", errors.toString());

        auditTrailMaint.insertAuditTrail(
                new AuditTrail("Rest", AuditTrail.MODULE_TRAINING, AuditTrail.FUNCTION_FAIL, "FAILED"));

    } finally {
        builder = null;
        googleJson = null;
        auditTrailMaint = null;
        candidateTrainingDetailMaint = null;
        candidateTrainingDetail = null;
        System.gc();
    }
    return Response.status(200).entity("[{\"isSuccessful\":" + isSuccessful + "}]").build();

}

From source file:com.quix.aia.cn.imo.rest.TrainingRest.java

License:Open Source License

/**
 * <p>//ww  w.  j av  a 2 s .c  o  m
 * This method inserts Candidate Training Result record.
 * </p>
 */
//"recruiterAgentCode":"014222",
//[{"perAgentName":"ABC","perAgentId":"38","branchCode":"014222","courseType":"description","passTime":"2015-06-06 08:00:00"}]
@POST
@Path("/pushResults")
@Consumes(MediaType.TEXT_PLAIN)
@Produces({ MediaType.APPLICATION_JSON })
public Response pushTrainingResults(@Context HttpServletRequest request, @Context ServletContext context,
        String jsonString) {
    log.log(Level.INFO, " Training --> push Results ");
    log.log(Level.INFO, " Training --> push Results  --> Data ...  ::::: " + jsonString);

    Gson googleJson = null;
    GsonBuilder builder = new GsonBuilder();
    AuditTrailMaintenance auditTrailMaint = new AuditTrailMaintenance();
    CandidateTrainingResultMaintenance candidateTrainingResultMaint = new CandidateTrainingResultMaintenance();
    CandidateTrainingResult candidateTrainingResult = null;
    int isSuccessful = 0;

    try {
        log.log(Level.INFO, "Training --> Saving Candidate Training Results ... ");

        builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
            @Override
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                    throws JsonParseException {
                Date date = LMSUtil.convertDateToyyyymmddhhmmssDashed(json.getAsString());
                if (null != date) {
                    return date;
                } else {
                    return LMSUtil.convertDateToyyyy_mm_dd(json.getAsString());
                }
            }
        });

        googleJson = builder.create();
        Type listType = new TypeToken<List<CandidateTrainingResult>>() {
        }.getType();
        List<CandidateTrainingResult> jsonObjList = googleJson.fromJson(jsonString, listType);
        candidateTrainingResult = jsonObjList.get(0);
        candidateTrainingResult.setCreationDate(new Date());

        candidateTrainingResultMaint.createNewCandidateTrainingResult(candidateTrainingResult, request);

        log.log(Level.INFO, "Training --> Candidate Training Results Saved successfully... ");
        isSuccessful = 1;
    } catch (Exception e) {
        log.log(Level.SEVERE, "Training --> Error in Saving Candidate Training Results.");
        log.log(Level.SEVERE, e.getMessage());
        e.printStackTrace();
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        LogsMaintenance logsMain = new LogsMaintenance();
        logsMain.insertLogs("TrainingRest", Level.SEVERE + "", errors.toString());

        auditTrailMaint.insertAuditTrail(
                new AuditTrail("Rest", AuditTrail.MODULE_TRAINING, AuditTrail.FUNCTION_FAIL, "FAILED"));

    } finally {
        builder = null;
        googleJson = null;
        auditTrailMaint = null;
        candidateTrainingResultMaint = null;
        candidateTrainingResult = null;
        System.gc();
    }
    return Response.status(200).entity("[{\"isSuccessful\":" + isSuccessful + "}]").build();
}

From source file:com.rackspacecloud.client.service_registry.ClientResponse.java

License:Apache License

private Object processResponse() throws IOException, ValidationException {
    Object data = null;//w w w  .  j  a va 2 s .c o  m
    HttpEntity entity = this.response.getEntity();
    int statusCode = response.getStatusLine().getStatusCode();

    if (statusCode == 400) {
        data = EntityUtils.toString(entity);

        ValidationException ex = new Gson().fromJson(data.toString(), ValidationException.class);
        throw ex;
    }

    if (entity != null) {
        data = EntityUtils.toString(entity);

        if (this.parseAsJson && this.responseType != null) {
            GsonBuilder builder = new GsonBuilder();
            Gson gson = builder.registerTypeAdapter(Event.class, new Event()).create();
            data = gson.fromJson(data.toString(), this.responseType);
        }
    }

    return data;
}

From source file:com.reactive.hzdfs.utils.GsonWrapper.java

License:Open Source License

private <T> void build() {
    GsonBuilder builder = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping();

    for (AbstractJsonSerializer<?> adaptor : typeAdapters) {
        builder.registerTypeAdapter(adaptor.getClassType(), adaptor);
    }//w w w .ja v a  2 s.  com
    gsonInstance = builder.create();
    alreadyBuilt = true;
}

From source file:com.reclabs.recomendar.esdriver.helper.JestResultHelper.java

License:Open Source License

/**
 * @param source/*from www .ja  v  a  2 s .co m*/
 * @param type
 * @param <T>
 * @return
 */
private static <T> T createSourceObject(Object source, Class<?> type) {
    Object obj = null;
    try {
        if (source instanceof Map) {
            GsonBuilder builder = new GsonBuilder();
            builder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            builder.registerTypeAdapter(RecMoney.class, new RecMoneyDeserializer());
            Gson gson = builder.create();
            String json = gson.toJson(source, Map.class);
            obj = gson.fromJson(json, type);
        } else {
            obj = type.cast(source);
        }

        //Fijamos la id
        Field[] fields = type.getDeclaredFields();
        for (Field field : fields) {
            if (StringHelper.equals(field.getName(), "id")) {
                try {
                    field.setAccessible(true);
                    Object value = field.get(obj);
                    if (value == null) {
                        field.set(obj, ((Map) source).get(ES_METADATA_ID));
                    }
                } catch (IllegalAccessException e) {
                    LOGGER.error("Unhandled exception occurred while getting annotated id from source");
                }
                break;
            }
        }

    } catch (Exception e) {
        LOGGER.error("Unhandled exception occurred while converting source to the object ."
                + type.getCanonicalName(), e);
    }
    return (T) obj;
}

From source file:com.redhat.thermostat.gateway.common.mongodb.response.MongoGsonFactory.java

License:Open Source License

public static Gson getGson() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Long.class, new LongTypeAdapter());
    gsonBuilder.registerTypeAdapter(long.class, new LongTypeAdapter());
    return gsonBuilder.create();
}

From source file:com.ritul.truckshare.RegisterActivity.DriverLicenseActivity.java

public void state_spiner() throws JSONException, UnsupportedEncodingException {
    ProgDialog.show();//from w ww .ja  v  a  2 s .  co m
    String ServiceUrl = "http://trucksharelle.showdemonow.com/api/services/TruckShareSystem/State/GetAllStates";
    AsyncHttpClient client = new AsyncHttpClient();
    client.get(ServiceUrl, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);

            try {
                if (response.getString("success").equalsIgnoreCase("true")) {
                    GsonBuilder gsonBuilder = new GsonBuilder();
                    gsonBuilder.registerTypeAdapter(StateSpinner.class, new StateSpinner());
                    Gson gson = gsonBuilder.create();
                    userHierarchy = gson.fromJson(response.get("result").toString(),
                            new TypeToken<List<StateSpinner>>() {
                            }.getType());

                    StateSpinnerAdapter adapter = new StateSpinnerAdapter(getApplicationContext(),
                            userHierarchy);
                    staticSpinner.setAdapter(adapter);
                    adapter.notifyDataSetChanged();
                    ProgDialog.dismiss();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (NullPointerException e) {

            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            Log.e("response_failure", responseString);
            ProgDialog.dismiss();
        }
    });
}

From source file:com.ritul.truckshare.RegisterActivity.TruckSizeActivity.java

public void trucktype() throws JSONException, UnsupportedEncodingException {
    ProgDialog.show();/*from www  .j  a v  a 2  s.  c  o m*/
    String ServiceUrl = "http://trucksharelle.showdemonow.com/api/services/TruckShareSystem/TruckType/GetAllTruckTypes";
    AsyncHttpClient client = new AsyncHttpClient();
    client.get(ServiceUrl, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);

            try {
                if (response.getString("success").equalsIgnoreCase("true")) {
                    GsonBuilder gsonBuilder = new GsonBuilder();
                    gsonBuilder.registerTypeAdapter(Truckothertype.class, new Truckothertype());
                    Gson gson = gsonBuilder.create();
                    userHierarchy = gson.fromJson(response.get("result").toString(),
                            new TypeToken<List<Truckothertype>>() {
                            }.getType());

                    Trucktype adapter = new Trucktype(getApplicationContext(), userHierarchy);
                    spinner.setAdapter(adapter);
                    adapter.notifyDataSetChanged();
                    ProgDialog.dismiss();

                }
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (NullPointerException e) {

            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            Log.e("response_failure", responseString);
            ProgDialog.dismiss();
        }
    });
}

From source file:com.ritul.truckshare.RegisterActivity.TruckSizeActivity.java

public void userdetail() throws JSONException {

    RequestParams params = new RequestParams();
    params.put("userName", RegisterActivity.email);
    RSMServer.get("GetUserProfileDetailByUserName?", params, new JsonHttpResponseHandler() {
        @Override/*from w  ww. ja v  a 2 s.c om*/
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            Log.e("Response", response + "");

            try {
                if (response.getString("success").equalsIgnoreCase("true")) {
                    GsonBuilder gsonBuilder = new GsonBuilder();
                    gsonBuilder.registerTypeAdapter(UserInformation.class, new UserInformation());
                    Gson gson = gsonBuilder.create();
                    UserInformation user = gson.fromJson(response.get("result").toString(),
                            new TypeToken<UserInformation>() {
                            }.getType());

                    RSMIT.getInstance().setUser(user);

                    try {
                        insert_driver();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                } else {
                    ProgDialog.dismiss();
                    Toast.makeText(getApplicationContext(), "Please try After Sometime", Toast.LENGTH_SHORT)
                            .show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
                ProgDialog.dismiss();
            } catch (NullPointerException e) {
                e.printStackTrace();
                ProgDialog.dismiss();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            snackbar = Snackbar.make(len, "Somthing Went to wrong with Server Please try after Sometime",
                    Snackbar.LENGTH_LONG);
            Log.e("response_failure", responseString);
            ProgDialog.dismiss();
        }
    });
}