List of usage examples for com.google.gson JsonDeserializer JsonDeserializer
JsonDeserializer
From source file:org.ambraproject.service.orcid.OrcidServiceImpl.java
License:Apache License
public OrcidServiceImpl() { /**//from ww w.j a va 2 s. c o m * This never changes, lets only create it once. */ GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(OrcidAuthorization.class, new JsonDeserializer<OrcidAuthorization>() { @Override public OrcidAuthorization deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { JsonObject json = (JsonObject) jsonElement; return OrcidAuthorization.builder().setAccessToken(json.get("access_token").getAsString()) .setTokenType(json.get("token_type").getAsString()) .setRefreshToken(json.get("refresh_token").getAsString()) .setExpiresIn(json.get("expires_in").getAsInt()).setScope(json.get("scope").getAsString()) .setOrcid(json.get("orcid").getAsString()).build(); } }); gson = gsonBuilder.create(); }
From source file:org.apache.falcon.regression.core.util.InstanceUtil.java
License:Apache License
public static APIResult hitUrl(String url, String method, String user) throws URISyntaxException, IOException, AuthenticationException, InterruptedException { BaseRequest request = new BaseRequest(url, method, user); HttpResponse response = request.run(); String responseString = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); LOGGER.info("The web service response is:\n" + Util.prettyPrintXmlOrJson(responseString)); APIResult result;/* w w w .j a v a2 s. c o m*/ if (url.contains("/summary/")) { result = new InstancesSummaryResult(APIResult.Status.FAILED, responseString); } else if (url.contains("/listing/")) { result = new FeedInstanceResult(APIResult.Status.FAILED, responseString); } else if (url.contains("instance/dependencies")) { result = new InstanceDependencyResult(APIResult.Status.FAILED, responseString); } else if (url.contains("instance/triage")) { result = new TriageResult(APIResult.Status.FAILED, responseString); } else { result = new InstancesResult(APIResult.Status.FAILED, responseString); } Assert.assertNotNull(result, "APIResult is null"); for (ResponseErrors error : ResponseErrors.values()) { if (responseString.contains(error.getError())) { return result; } } final String[] errorStrings = { "(FEED) not found", "is beforePROCESS start", "is after end date", "is after PROCESS's end", "is before PROCESS's start", "is before the entity was scheduled", }; for (String error : errorStrings) { if (responseString.contains(error)) { return result; } } try { result = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { @Override public Date deserialize(JsonElement json, Type t, JsonDeserializationContext c) { return new DateTime(json.getAsString()).toDate(); } }).create().fromJson(responseString, getClassOfResult(url)); } catch (JsonSyntaxException e) { Assert.fail("Not a valid json:\n" + responseString); } LOGGER.info("statusCode: " + response.getStatusLine().getStatusCode()); LOGGER.info("message: " + result.getMessage()); LOGGER.info("APIResult.Status: " + result.getStatus()); return result; }
From source file:org.eclipse.mylyn.internal.gerrit.core.client.JSonSupport.java
License:Open Source License
public JSonSupport() { TypeToken<Map<Id, PatchSetApproval>> approvalMapType = new TypeToken<Map<ApprovalCategory.Id, PatchSetApproval>>() { };/* www. j a va 2s . co m*/ ExclusionStrategy exclustionStrategy = new ExclusionStrategy() { public boolean shouldSkipField(FieldAttributes f) { // commentLinks requires instantiation of com.google.gwtexpui.safehtml.client.RegexFindReplace which is not on classpath if (f.getDeclaredClass() == List.class && f.getName().equals("commentLinks") //$NON-NLS-1$ && f.getDeclaringClass() == GerritConfig.class) { return true; } if (f.getDeclaredClass() == Map.class && f.getName().equals("given")) { //$NON-NLS-1$ //return true; } // GSon 2.1 fails to deserialize the SubmitType enum if (f.getDeclaringClass() == Project.class && f.getName().equals("submitType")) { //$NON-NLS-1$ return true; } return false; } public boolean shouldSkipClass(Class<?> clazz) { return false; } }; gson = JsonServlet.defaultGsonBuilder() .registerTypeAdapter(JSonResponse.class, new JSonResponseDeserializer()) .registerTypeAdapter(Edit.class, new JsonDeserializer<Edit>() { public Edit deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (json.isJsonArray()) { JsonArray array = json.getAsJsonArray(); if (array.size() == 4) { return new Edit(array.get(0).getAsInt(), array.get(1).getAsInt(), array.get(2).getAsInt(), array.get(3).getAsInt()); } } return new Edit(0, 0); } }) // ignore GerritForge specific AuthType "TEAMFORGE" which is unknown to Gerrit .registerTypeAdapter(AuthType.class, new JsonDeserializer<AuthType>() { @Override public AuthType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { String jsonString = json.getAsString(); if (jsonString != null) { try { return AuthType.valueOf(jsonString); } catch (IllegalArgumentException e) { // ignore the error since the connector does not make use of AuthType //GerritCorePlugin.logWarning("Ignoring unkown authentication type: " + jsonString, e); } } return null; } }) .registerTypeAdapter(approvalMapType.getType(), new JsonDeserializer<Map<Id, PatchSetApproval>>() { @Override public Map<Id, PatchSetApproval> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { // Gerrit 2.2: the type of PatchSetPublishDetail.given changed from a map to a list Map<Id, PatchSetApproval> map = new HashMap<ApprovalCategory.Id, PatchSetApproval>(); if (json.isJsonArray()) { JsonArray array = json.getAsJsonArray(); for (Iterator<JsonElement> it = array.iterator(); it.hasNext();) { JsonElement element = it.next(); Id key = context.deserialize(element, Id.class); if (key.get() != null) { // Gerrit < 2.1.x: json is map element = it.next(); } PatchSetApproval value = context.deserialize(element, PatchSetApproval.class); if (key.get() == null) { // Gerrit 2.2: json is a list, deduct key from value key = value.getCategoryId(); } map.put(key, value); } } return map; } }).setExclusionStrategies(exclustionStrategy).create(); }
From source file:org.eclipse.packagedrone.repo.channel.apm.ChannelModelProvider.java
License:Open Source License
static Gson createGson() { final GsonBuilder builder = new GsonBuilder(); builder.setPrettyPrinting();/*from w ww. j a v a 2 s.c o m*/ builder.setLongSerializationPolicy(LongSerializationPolicy.STRING); builder.setDateFormat(DATE_FORMAT); builder.registerTypeAdapter(MetaKey.class, new JsonDeserializer<MetaKey>() { @Override public MetaKey deserialize(final JsonElement json, final Type type, final JsonDeserializationContext ctx) throws JsonParseException { return MetaKey.fromString(json.getAsString()); } }); return builder.create(); }
From source file:org.erlymon.monitor.dagger.module.GsonModule.java
License:Open Source License
@Provides @Singleton/*from w ww . j a v a2s .c o m*/ Gson provideGson(SharedPreferences sharedPreferences) { return new GsonBuilder() //.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") .registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.ENGLISH); @Override public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try { return new Date(df.parse(json.getAsString()).getTime()); } catch (final java.text.ParseException e) { //e.printStackTrace(); return null; } } }).setVersion(sharedPreferences.getFloat("protocolVersion", 3.4f)) //.setVersion(3.4) .create(); }
From source file:org.geppetto.frontend.controllers.ConnectionHandler.java
License:Open Source License
/** * @return/*from w w w . j a va 2s. c om*/ */ private Gson getGson() { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { @Override public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return new Date(json.getAsJsonPrimitive().getAsLong()); } }); return builder.create(); }
From source file:org.lightcouch.CouchDbClientBase.java
License:Apache License
/** * Builds {@link Gson} and registers any required serializer/deserializer. * @return {@link Gson} instance/* w w w .j a va 2 s. co m*/ */ private Gson initGson(GsonBuilder gsonBuilder) { gsonBuilder.registerTypeAdapter(JsonObject.class, new JsonDeserializer<JsonObject>() { public JsonObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return json.getAsJsonObject(); } }); gsonBuilder.registerTypeAdapter(JsonObject.class, new JsonSerializer<JsonObject>() { @Override public JsonElement serialize(JsonObject jsonObject, Type type, JsonSerializationContext jsonSerializationContext) { return jsonObject; } }); return gsonBuilder.create(); }
From source file:org.netbeans.rest.application.config.GsonMessageBodyHandler.java
private Gson getGson() { if (gson == null) { JsonSerializer<Date> ser = new JsonSerializer<Date>() { @Override// www .j a va 2s. com public JsonElement serialize(Date src, Type type, JsonSerializationContext jsc) { return src == null ? null : new JsonPrimitive(src.getTime()); } }; JsonDeserializer<Date> deser = new JsonDeserializer<Date>() { @Override public Date deserialize(JsonElement json, Type type, JsonDeserializationContext jdc) throws JsonParseException { return json == null ? null : new Date(json.getAsLong()); } }; final GsonBuilder gsonBuilder = new GsonBuilder(); gson = gsonBuilder.registerTypeAdapter(Date.class, ser).registerTypeAdapter(Date.class, deser).create(); } return gson; }
From source file:org.sociotech.communitymashup.source.mendeley.sdkadaption.AdaptedProfileServiceImpl.java
License:Open Source License
@Override protected GsonBuilder getGsonBuilder() { GsonBuilder builder = super.getGsonBuilder(); builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { @Override//from w ww . ja v a 2 s .c o m public Date deserialize(JsonElement arg0, java.lang.reflect.Type arg1, JsonDeserializationContext arg2) throws JsonParseException { DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { String value = arg0.getAsString(); date = (Date) formatter.parse(value); } catch (ParseException e) { return null; } return date; } }); return builder; }
From source file:org.tinymediamanager.scraper.fanarttv.FanartTv.java
License:Apache License
protected GsonBuilder getGsonBuilder() { GsonBuilder builder = new GsonBuilder(); // class types builder.registerTypeAdapter(Integer.class, new JsonDeserializer<Integer>() { @Override/*ww w. ja va2 s .c om*/ public Integer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try { return Integer.valueOf(json.getAsInt()); } catch (NumberFormatException e) { return 0; } } }); builder.registerTypeAdapter(Date.class, new DateTypeAdapter()); builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); return builder; }