List of usage examples for com.google.gson JsonDeserializer JsonDeserializer
JsonDeserializer
From source file:com.quix.aia.cn.imo.rest.TrainingRest.java
License:Open Source License
/** * <p>//from ww w.j a va2 s . c om * 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.uwetrottmann.tmdb.TmdbHelper.java
License:Apache License
/** * Create a {@link com.google.gson.GsonBuilder} and register all of the custom types needed in * order to properly deserialize complex TMDb-specific types. * * @return Assembled GSON builder instance. *//*from w w w . j a v a 2s. c om*/ public static GsonBuilder getGsonBuilder() { GsonBuilder builder = new GsonBuilder(); // class types builder.registerTypeAdapter(Integer.class, new JsonDeserializer<Integer>() { @Override public Integer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try { return Integer.valueOf(json.getAsInt()); } catch (NumberFormatException e) { return null; } } }); builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { @Override public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try { return JSON_STRING_DATE.parse(json.getAsString()); } catch (ParseException e) { return null; } } }); return builder; }
From source file:com.vimeo.networking.utils.ISO8601.java
License:Open Source License
public static JsonDeserializer<Date> getDateDeserializer() { return new JsonDeserializer<Date>() { @Override/*from www . j a va2 s . co m*/ public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try { return json == null ? null : toDate(json.getAsString()); } catch (ParseException e) { // Return an null date if it is formatted incorrectly System.out.println("Incorrectly formatted date sent from server"); return null; } } }; }
From source file:com.wialon.core.Session.java
License:Apache License
/** * Initialize Wialon session/*w w w . j av a 2 s . c o m*/ * @param baseUrl */ public boolean initSession(String baseUrl) { this.baseUrl = baseUrl; this.renderer = new Renderer(); this.messagesLoader = new MessagesLoader(); if (httpClient == null) httpClient = RemoteHttpClient.getInstance(); if (jsonParser == null) jsonParser = new JsonParser(); if (gson == null) gson = new GsonBuilder().registerTypeAdapter(String.class, new JsonDeserializer<String>() { @Override public String deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { return jsonElement.isJsonPrimitive() ? jsonElement.getAsString() : jsonElement.toString(); } }).create(); return initialized = true; }
From source file:com.zuoxiaolong.blog.sdk.BlogInterfaceHandler.java
License:Apache License
/** * ?????//from www . java 2s .com * * @return */ public static List<ArticleRankResponseDto> getArticleRank() throws Exception { HttpRequest request = new HttpRequest(); String responseString = request.doGet(BlogSdkPropertiesUtil.getProperty("articleRankUrl")); System.out.println(responseString); // Creates the json object which will manage the information received GsonBuilder gsonBuilder = new GsonBuilder(); // Register an adapter to manage the date types as long values gsonBuilder.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 = gsonBuilder.create(); Type articleRankResponseDtoListType = new TypeToken<List<ArticleRankResponseDto>>() { }.getType(); List<ArticleRankResponseDto> articleRankResponseDtos = gson.fromJson(responseString, articleRankResponseDtoListType); return articleRankResponseDtos; }
From source file:de.arkraft.jenkins.JenkinsHelper.java
License:Apache License
public static GsonBuilder getGsonBuilder() { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(DateTime.class, new JsonDeserializer<DateTime>() { @Override//w w w .ja v a 2 s .c om public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { // using the correct parser right away should save init time compared to new DateTime(<string>) return ISO_8601_WITH_MILLIS.parseDateTime(json.getAsString()); } }); builder.registerTypeAdapter(DateTime.class, new JsonSerializer<DateTime>() { @Override public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.toString()); } }); builder.registerTypeAdapter(Duration.class, new JsonDeserializer() { @Override public Object deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { return Duration.parse("PT" + json.getAsString() + "S"); } }); builder.registerTypeAdapter(Action.class, new JsonDeserializer<Action>() { @Override public Action deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { JsonObject object = ((JsonObject) jsonElement); if (object.has("causes")) { JsonElement element = object.get("causes"); if (element.isJsonArray()) { return jsonDeserializationContext.deserialize(element, Causes.class); } } if (object.has("failCount")) { return jsonDeserializationContext.deserialize(object, CountAction.class); } return null; } }); builder.registerTypeAdapter(ChangeSet.class, new JsonDeserializer<ChangeSet>() { @Override public ChangeSet deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException { ChangeSet changeSet = new ChangeSet(); JsonObject object = (JsonObject) jsonElement; if (object.has("items") && object.get("items").isJsonArray()) { for (JsonElement element : object.get("items").getAsJsonArray()) { ChangeSet.Change change = context.deserialize(element, ChangeSet.Change.class); changeSet.add(change); } } if (object.has("kind")) { changeSet.setKind(object.get("kind").getAsString()); } return changeSet; } }); builder.registerTypeAdapter(Duration.class, new JsonSerializer<Duration>() { @Override public JsonElement serialize(Duration duration, Type type, JsonSerializationContext jsonSerializationContext) { return new JsonPrimitive(duration.toString().replace("PT", "").replace("S", "")); } }); builder.registerTypeAdapter(EditType.class, new JsonDeserializer<EditType>() { @Override public EditType deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { return EditType.byName(jsonElement.getAsString()); } }); builder.registerTypeAdapter(HealthIcon.class, new JsonDeserializer<HealthIcon>() { @Override public HealthIcon deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { return HealthIcon.fromName(jsonElement.toString()); } }); builder.registerTypeAdapter(Queue.class, new JsonDeserializer<Queue>() { @Override public Queue deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException { Queue queue = new Queue(); JsonObject jsonObject = (JsonObject) jsonElement; if (jsonObject.has("items") && jsonObject.get("items").isJsonArray()) { for (JsonElement element : jsonObject.get("items").getAsJsonArray()) { Queue.Item build = context.deserialize(element, Queue.Item.class); queue.add(build); } } return queue; } }); builder.registerTypeAdapter(JobCollection.class, new JsonDeserializer<JobCollection>() { @Override public JobCollection deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { JobCollection jobs = new JobCollection(); JsonObject object = (JsonObject) json; if (object.has("jobs") && object.get("jobs").isJsonArray()) { for (JsonElement element : object.get("jobs").getAsJsonArray()) { Job job = context.deserialize(element, Job.class); jobs.add(job); } } return jobs; } }); builder.registerTypeAdapter(BallColor.class, new JsonDeserializer<BallColor>() { @Override public BallColor deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext json) throws JsonParseException { return BallColor.valueOf(jsonElement.getAsString().toUpperCase()); } }); return builder; }
From source file:de.symeda.sormas.app.rest.RetroProvider.java
License:Open Source License
private RetroProvider(Context context) throws ServerConnectionException, ServerCommunicationException, ApiVersionException { lastConnectionId = this.hashCode(); this.context = context; RuntimeTypeAdapterFactory<ClassificationCriteriaDto> classificationCriteriaFactory = RuntimeTypeAdapterFactory .of(ClassificationCriteriaDto.class, "type") .registerSubtype(ClassificationAllOfCriteriaDto.class, "ClassificationAllOfCriteriaDto") .registerSubtype(ClassificationCaseCriteriaDto.class, "ClassificationCaseCriteriaDto") .registerSubtype(ClassificationNoneOfCriteriaDto.class, "ClassificationNoneOfCriteriaDto") .registerSubtype(ClassificationPersonAgeBetweenYearsCriteriaDto.class, "ClassificationPersonAgeBetweenYearsCriteriaDto") .registerSubtype(ClassificationPathogenTestPositiveResultCriteriaDto.class, "ClassificationPathogenTestPositiveResultCriteriaDto") .registerSubtype(ClassificationXOfCriteriaDto.class, "ClassificationXOfCriteriaDto") .registerSubtype(ClassificationEpiDataCriteriaDto.class, "ClassificationEpiDataCriteriaDto") .registerSubtype(ClassificationNotInStartDateRangeCriteriaDto.class, "ClassificationNotInStartDateRangeCriteriaDto") .registerSubtype(ClassificationSymptomsCriteriaDto.class, "ClassificationSymptomsCriteriaDto") .registerSubtype(ClassificationPathogenTestCriteriaDto.class, "ClassificationPathogenTestCriteriaDto") .registerSubtype(ClassificationXOfCriteriaDto.ClassificationXOfSubCriteriaDto.class, "ClassificationXOfSubCriteriaDto") .registerSubtype(ClassificationXOfCriteriaDto.ClassificationOneOfCompactCriteriaDto.class, "ClassificationOneOfCompactCriteriaDto") .registerSubtype(ClassificationAllOfCriteriaDto.ClassificationAllOfCompactCriteriaDto.class, "ClassificationAllOfCompactCriteriaDto"); Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (json.isJsonNull()) { return null; }//from w w w.j ava 2 s . com long milliseconds = json.getAsLong(); return new Date(milliseconds); } }).registerTypeAdapter(Date.class, new JsonSerializer<Date>() { @Override public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { if (src == null) { return JsonNull.INSTANCE; } return new JsonPrimitive(src.getTime()); } }).registerTypeAdapterFactory(classificationCriteriaFactory).create(); // Basic auth as explained in https://futurestud.io/tutorials/android-basic-authentication-with-retrofit String authToken = Credentials.basic(ConfigProvider.getUsername(), ConfigProvider.getPassword()); AuthenticationInterceptor interceptor = new AuthenticationInterceptor(authToken); OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); httpClient.connectTimeout(20, TimeUnit.SECONDS); httpClient.readTimeout(60, TimeUnit.SECONDS); // for infrastructure data httpClient.writeTimeout(30, TimeUnit.SECONDS); // adds "Accept-Encoding: gzip" by default httpClient.addInterceptor(interceptor); // header for logging purposes httpClient.addInterceptor(chain -> { Request original = chain.request(); Request.Builder builder = original.newBuilder(); User user = ConfigProvider.getUser(); if (user != null) { builder.header("User", DataHelper.getShortUuid(user.getUuid())); builder.header("Connection", String.valueOf(lastConnectionId)); // not sure if this is a good solution } builder.method(original.method(), original.body()); return chain.proceed(builder.build()); }); retrofit = new Retrofit.Builder().baseUrl(ConfigProvider.getServerRestUrl()) .addConverterFactory(GsonConverterFactory.create(gson)).client(httpClient.build()).build(); checkCompatibility(); updateLocale(); }
From source file:fi.vm.sade.organisaatio.business.impl.OrganisaatioTarjonta.java
License:EUPL
private void initGson() { GsonBuilder gsonBuilder = new GsonBuilder(); // Jtetn oid pois sill KoulutusHakutulosV1RDTO sislt kaksi oid kentt gsonBuilder.setExclusionStrategies(new ExclusionStrategy() { @Override//from ww w . j a v a 2s . co m public boolean shouldSkipField(FieldAttributes fieldAttributes) { return "oid".equals(fieldAttributes.getName()); } @Override public boolean shouldSkipClass(Class<?> arg0) { return false; } }); // Rekisteridn adapteri, jolla hoidetaan date tyyppi long arvona gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { @Override public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return new Date(json.getAsJsonPrimitive().getAsLong()); } }); gson = gsonBuilder.create(); }
From source file:io.bouquet.v4.GsonFactory.java
License:Apache License
/** * JSON constructor.// w ww . j ava 2 s.c o m * * @param getClient() An instance of ApiClient */ public GsonFactory(ApiClient apiClient) { this.apiClient = apiClient; JsonDeserializer<ChosenMetric> chosenMetricDeserializer = new JsonDeserializer<ChosenMetric>() { @Override public ChosenMetric deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (json.isJsonObject()) { JsonObject jsonObject = json.getAsJsonObject(); Expression expression = gson.fromJson(jsonObject, Expression.class); return new ChosenMetric(expression); } else { return new ChosenMetric(json.getAsString()); } } }; JsonSerializer<ChosenMetric> chosenMetricSerializer = new JsonSerializer<ChosenMetric>() { @Override public JsonElement serialize(ChosenMetric src, Type typeOfSrc, JsonSerializationContext context) { if (src.getId() != null) { return new JsonPrimitive(src.getId()); } else { return context.serialize(src.getExpression(), Expression.class); } } }; JsonDeserializer<FacetMember> facetMemberDeserializer = new JsonDeserializer<FacetMember>() { @Override public FacetMember deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (json.isJsonObject()) { JsonObject jsonObject = json.getAsJsonObject(); if (jsonObject != null) { if ("i".equals(jsonObject.get("type").getAsString())) { return gson.fromJson(jsonObject, FacetMemberInterval.class); } else if ("v".equals(jsonObject.get("type").getAsString())) { return gson.fromJson(jsonObject, FacetMemberString.class); } else { // throw new ApiException("Invalid facet type"); return null; } } // throw new ApiException("Invalid facet type"); return null; } else { // throw new ApiException("Invalid facet type"); return null; } } }; JsonSerializer<FacetMember> facetMemberSerializer = new JsonSerializer<FacetMember>() { @Override public JsonElement serialize(FacetMember src, Type typeOfSrc, JsonSerializationContext context) { if (src instanceof FacetMemberInterval) { return context.serialize(src, FacetMemberInterval.class); } else if (src instanceof FacetMemberString) { return context.serialize(src, FacetMemberString.class); } else { return null; } } }; JsonDeserializer<Credentials> credentialsDeserializer = new JsonDeserializer<Credentials>() { @Override public Credentials deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (json.isJsonObject()) { JsonObject jsonObject = json.getAsJsonObject(); if (jsonObject != null) { if ("API".equals(jsonObject.get("type").getAsString())) { return gson.fromJson(jsonObject, APICredentials.class); } else if ("DBMS".equals(jsonObject.get("type").getAsString())) { return gson.fromJson(jsonObject, DBMSCredentials.class); } else if ("REFRESH".equals(jsonObject.get("type").getAsString())) { return gson.fromJson(jsonObject, OAuth2RefreshCredentials.class); } else { // throw new ApiException("Invalid facet type"); return null; } } // throw new ApiException("Invalid facet type"); return null; } else { // throw new ApiException("Invalid facet type"); return null; } } }; JsonSerializer<Credentials> credentialsSerializer = new JsonSerializer<Credentials>() { @Override public JsonElement serialize(Credentials src, Type typeOfSrc, JsonSerializationContext context) { if (src instanceof APICredentials) { return context.serialize(src, APICredentials.class); } else if (src instanceof DBMSCredentials) { return context.serialize(src, DBMSCredentials.class); } else if (src instanceof OAuth2RefreshCredentials) { return context.serialize(src, OAuth2RefreshCredentials.class); } else { return null; } } }; JsonDeserializer<Col> colSerializer = new JsonDeserializer<Col>() { @Override public Col deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (json.isJsonObject()) { JsonObject jsonObject = json.getAsJsonObject(); Col col = new Col(); if (jsonObject.get("id") != null && jsonObject.get("id").isJsonNull() == false) { col.setId(jsonObject.get("id").getAsString()); } if (jsonObject.get("name") != null && jsonObject.get("name").isJsonNull() == false) { col.setName(jsonObject.get("name").getAsString()); } if (jsonObject.get("definiti") != null && jsonObject.get("definiti").isJsonNull() == false) { col.setDefinition(jsonObject.get("definition").getAsString()); } if (jsonObject.get("extendedType") != null && jsonObject.get("extendedType").isJsonNull() == false) { col.setExtendedType(gson.fromJson(jsonObject.get("extendedType"), ExtendedType.class)); } if (jsonObject.get("originType") != null && jsonObject.get("originType").isJsonNull() == false) { col.setOriginType(OriginType.valueOf(jsonObject.get("originType").getAsString())); } if (jsonObject.get("description") != null && jsonObject.get("description").isJsonNull() == false) { col.setDescription(jsonObject.get("description").getAsString()); } if (jsonObject.get("format") != null && jsonObject.get("format").isJsonNull() == false) { col.setFormat(jsonObject.get("format").getAsString()); } if (jsonObject.get("pos") != null && jsonObject.get("pos").isJsonNull() == false) { col.setPos(jsonObject.get("pos").getAsInt()); } if (jsonObject.get("lname") != null && jsonObject.get("lname").isJsonNull() == false) { col.setLname(jsonObject.get("lname").getAsString()); } if (jsonObject.get("role") != null && jsonObject.get("role").isJsonNull() == false) { col.setRole(Role.valueOf(jsonObject.get("role").getAsString())); } if (col.getRole() != null && jsonObject.get("pk") != null && jsonObject.get("pk").isJsonNull() == false) { if (Role.DOMAIN == col.getRole()) { col.setPk(gson.fromJson(jsonObject.get("pk"), DimensionPK.class)); } else if (Role.DATA == col.getRole()) { col.setPk(gson.fromJson(jsonObject.get("pk"), MetricPK.class)); } } return col; } else { return null; } } }; gson = new GsonBuilder().registerTypeAdapter(Date.class, new DateAdapter(apiClient)) .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) .registerTypeAdapter(FacetMember.class, facetMemberDeserializer) .registerTypeAdapter(FacetMember.class, facetMemberSerializer) .registerTypeAdapter(ChosenMetric.class, chosenMetricDeserializer) .registerTypeAdapter(ChosenMetric.class, chosenMetricSerializer) .registerTypeAdapter(Credentials.class, credentialsDeserializer) .registerTypeAdapter(ChosenMetric.class, credentialsSerializer) .registerTypeAdapter(Col.class, colSerializer).create(); }
From source file:it.delli.mwebc.servlet.MWebCManager.java
License:Open Source License
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/* ww w. ja v a 2 s.c o m*/ response.setContentType("text/xml"); String action = request.getParameter("action"); JsonObject data = new GsonBuilder() .registerTypeAdapter(JsonObject.class, new JsonDeserializer<JsonObject>() { public JsonObject deserialize(JsonElement json, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return json.getAsJsonObject(); } }).create().fromJson(request.getParameter("data"), JsonObject.class); log.info("Begin managing client event request"); log.debug("Client event request data: " + data.toString()); Application application = (Application) request.getSession().getAttribute("application"); application.setHttpServletRequest(request); application.setHttpServletResponse(response); Page page = application.getPage(data.get("pageName").getAsString()); JsonElement widgets = data.get("widgets"); if (widgets != null) { for (int i = 0; i < widgets.getAsJsonArray().size(); i++) { updateServerWidget(page, widgets.getAsJsonArray().get(i).getAsJsonObject()); } } Command command = application.getCommand(action); command.execute(page, data); PrintWriter out = response.getWriter(); application.printJavaScriptStream(out); out.flush(); out.close(); cleanRemovedWidgets(page); log.info("End managing client event request"); } catch (Exception e) { log.error("Exception in forwarding control to server", e); throw new ServletException(e); } }