List of usage examples for com.google.gson JsonSerializer JsonSerializer
JsonSerializer
From source file:cz.cvut.fit.vmw.api.PhotoResource.java
@GET @Produces("application/json") public Response getAllPhotos() { List<PhotoFile> result = photoFileDAO.findAll(); JsonSerializer<Date> ser = new JsonSerializer<Date>() { @Override/*from w w w .j a va 2 s . co m*/ public JsonElement serialize(Date src, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) { return src == null ? null : new JsonPrimitive(src.getTime()); } }; Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation() .registerTypeAdapter(Date.class, ser).create(); return Response.ok(gson.toJson(result)).encoding("UTF-8").build(); }
From source file:cz.cvut.fit.vmw.api.PhotoResource.java
@GET @Path("find10/id/{id}") @Produces("application/json") public Response findBest10ToID(@PathParam("id") final Integer id) { List<PhotoFile> result = new ArrayList<>(); PhotoFile orig = photoFileDAO.find(id); if (orig != null) { List<PhotoFile> dbImages = photoFileDAO.findAll(); dbImages = dbImages.subList(0, 15); dbImages.remove(orig);//from w ww . j a v a 2 s . c om // result = SURFApi.findMatches2(orig, dbImages); result = SURFApi.findParallel(orig, dbImages); } JsonSerializer<Date> ser = new JsonSerializer<Date>() { @Override public JsonElement serialize(Date src, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) { return src == null ? null : new JsonPrimitive(src.getTime()); } }; Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation() .registerTypeAdapter(Date.class, ser).create(); return Response.ok(gson.toJson(result)).encoding("UTF-8").build(); }
From source file:cz.cvut.fit.vmw.api.PhotoResource.java
@POST @Path("upload") @Consumes("multipart/form-data") @Produces("application/json") public Response uploadPhoto(@MultipartForm UploadPhotoFile uploadedPhoto) { PhotoFile photo = new PhotoFile(); photo.setCreateDate(new Date()); photo.setData(uploadedPhoto.getData()); photo.setId(null);//w ww. ja v a2 s . com LOG.info(uploadedPhoto.getData().toString()); photoFileDAO.create(photo); List<PhotoFile> result = photoFileDAO.findAll(); JsonSerializer<Date> ser = new JsonSerializer<Date>() { @Override public JsonElement serialize(Date src, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) { return src == null ? null : new JsonPrimitive(src.getTime()); } }; Gson gson = new GsonBuilder().serializeNulls().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting() .registerTypeAdapter(Date.class, ser).create(); return Response.ok(gson.toJson(result)).encoding("UTF-8").build(); }
From source file:cz.cvut.fit.vmw.api.PhotoResource.java
@POST @Path("upload64") @Consumes("application/json") @Produces("application/json") public Response uploadPhoto64(UploadPhotoFile64 photoBase64) { byte[] photoData = null; // try { // photoData = Base64.getDecoder().decode(URLDecoder.decode(photoBase64.getData(), "UTF-8").getBytes(StandardCharsets.ISO_8859_1)); photoData = DatatypeConverter.parseBase64Binary(photoBase64.getData()); // photoData = Base64.getDecoder().decode(photoBase64.getData().getBytes(StandardCharsets.UTF_8)); // Base64.getDecoder().de // } catch (UnsupportedEncodingException ex) { // Logger.getLogger(PhotoResource.class.getName()).log(Level.SEVERE, null, ex); // }//from w ww . ja v a2 s.c o m PhotoFile photo = new PhotoFile(); photo.setCreateDate(new Date()); photo.setData(photoData); photo.setId(null); photoFileDAO.create(photo); LOG.info("UPLOADED"); List<PhotoFile> dbImages = photoFileDAO.findAll(); List<PhotoFile> result = new ArrayList<>(); PhotoFile orig = dbImages.get(dbImages.size() - 1); if (orig != null) { // dbImages = dbImages.subList(0, 15); dbImages.remove(orig); // result = SURFApi.findMatches2(orig, dbImages); result = SURFApi.findParallel(orig, dbImages); } JsonSerializer<Date> ser = new JsonSerializer<Date>() { @Override public JsonElement serialize(Date src, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) { return src == null ? null : new JsonPrimitive(src.getTime()); } }; Gson gson = new GsonBuilder().serializeNulls().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting() .registerTypeAdapter(Date.class, ser).create(); // LOG.info(gson.toJson(result)); return Response.ok(gson.toJson(result)).encoding("UTF-8").build(); }
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//from www.ja v a 2s. c o m 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; }// ww w .j a va 2 s .c o m 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:edu.mit.media.funf.FunfManager.java
License:Open Source License
/** * Get a gson builder with the probe factory built in * @return//from w w w .j a v a2s . co m */ public static GsonBuilder getGsonBuilder(Context context) { return new GsonBuilder().registerTypeAdapterFactory(getProbeFactory(context)) .registerTypeAdapterFactory(getActionFactory(context)) .registerTypeAdapterFactory(getPipelineFactory(context)) .registerTypeAdapterFactory(getDataSourceFactory(context)) .registerTypeAdapterFactory(new ConfigurableRuntimeTypeAdapterFactory<Schedule>(context, Schedule.class, BasicSchedule.class)) .registerTypeAdapterFactory(new ConfigurableRuntimeTypeAdapterFactory<ConfigUpdater>(context, ConfigUpdater.class, HttpConfigUpdater.class)) .registerTypeAdapterFactory(new ConfigurableRuntimeTypeAdapterFactory<FileArchive>(context, FileArchive.class, DefaultArchive.class)) .registerTypeAdapterFactory(new ConfigurableRuntimeTypeAdapterFactory<RemoteFileArchive>(context, RemoteFileArchive.class, HttpArchive.class)) .registerTypeAdapterFactory( new ConfigurableRuntimeTypeAdapterFactory<DataListener>(context, DataListener.class, null)) .registerTypeAdapter(DefaultSchedule.class, new DefaultScheduleSerializer()) .registerTypeAdapter(Class.class, new JsonSerializer<Class<?>>() { @Override public JsonElement serialize(Class<?> src, Type typeOfSrc, JsonSerializationContext context) { return src == null ? JsonNull.INSTANCE : new JsonPrimitive(src.getName()); } }); }
From source file:edu.mit.media.funf.probe.builtin.AccountsProbe.java
License:Open Source License
@Override protected GsonBuilder getGsonBuilder() { GsonBuilder builder = super.getGsonBuilder(); builder.registerTypeAdapter(Account.class, new JsonSerializer<Account>() { @Override/*from w w w . j a v a2 s .c om*/ public JsonElement serialize(Account src, Type typeOfSrc, JsonSerializationContext context) { JsonObject account = new JsonObject(); account.addProperty(NAME, sensitiveData(src.name)); account.addProperty(TYPE, src.type); return account; } }); return builder; }
From source file:funf.FunfManager.java
License:Open Source License
/** * Get a gson builder with the probe factory built in * @return//from w w w.j a va 2 s .c om */ public static GsonBuilder getGsonBuilder(Context context) { return new GsonBuilder().registerTypeAdapterFactory(getProbeFactory(context)) .registerTypeAdapterFactory(getPipelineFactory(context)) .registerTypeAdapterFactory(new ConfigurableRuntimeTypeAdapterFactory<Schedule>(context, Schedule.class, BasicSchedule.class)) .registerTypeAdapterFactory(new ConfigurableRuntimeTypeAdapterFactory<ConfigUpdater>(context, ConfigUpdater.class, HttpConfigUpdater.class)) .registerTypeAdapterFactory(new ConfigurableRuntimeTypeAdapterFactory<FileArchive>(context, FileArchive.class, DefaultArchive.class)) .registerTypeAdapterFactory(new ConfigurableRuntimeTypeAdapterFactory<RemoteFileArchive>(context, RemoteFileArchive.class, HttpArchive.class)) .registerTypeAdapter(DefaultSchedule.class, new DefaultScheduleSerializer()) .registerTypeAdapter(Class.class, new JsonSerializer<Class<?>>() { @Override public JsonElement serialize(Class<?> src, Type typeOfSrc, JsonSerializationContext context) { return src == null ? JsonNull.INSTANCE : new JsonPrimitive(src.getName()); } }); }
From source file:info.raack.appliancedetection.evaluation.web.EvaluationController.java
License:Open Source License
@RequestMapping(value = "/evaluation/{id}", method = RequestMethod.GET) public void getEvaluationData(@PathVariable("id") String simulationId, @RequestParam("algorithmId") int algorithmId, @RequestParam(value = "start", required = false) Double startMillis, @RequestParam(value = "end", required = false) Double endMillis, @RequestParam(value = "ticks", required = false) Integer ticks, HttpServletRequest request, HttpServletResponse response) throws IOException { // TODO - for now, just use the naive algorithm's energy measurements. Date start = null;/*from ww w . j a v a 2 s .c o m*/ Date end = null; if (startMillis != null && endMillis != null) { start = new Date(startMillis.longValue()); end = new Date(endMillis.longValue()); } else if (startMillis != null && endMillis == null) { // if only start or end are provided, create a one day span Calendar c = new GregorianCalendar(); c.setTimeInMillis(startMillis.longValue()); start = c.getTime(); } else if (startMillis == null && endMillis != null) { // if only start or end are provided, create a one day span Calendar c = new GregorianCalendar(); c.setTimeInMillis(endMillis.longValue()); end = c.getTime(); } if (ticks == null) { ticks = 300; } Evaluation evaluation = simulationService.getEvaluation(algorithmId, simulationId, start, end, true); if (evaluation == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } EvaluationWrapper wrapper = new EvaluationWrapper(evaluation); JsonSerializer<EnergyTimestep> dateSerializer = new JsonSerializer<EnergyTimestep>() { // serialize date to milliseconds since epoch public JsonElement serialize(EnergyTimestep energyTimestep, Type me, JsonSerializationContext arg2) { JsonArray object = new JsonArray(); object.add(new JsonPrimitive(energyTimestep.getStartTime().getTime())); object.add(new JsonPrimitive(energyTimestep.getEnergyConsumed())); return object; } }; String dataJS = new GsonBuilder().registerTypeAdapter(EnergyTimestep.class, dateSerializer) .excludeFieldsWithModifiers(Modifier.STATIC).setExclusionStrategies(new ExclusionStrategy() { // skip logger public boolean shouldSkipClass(Class<?> clazz) { return clazz.equals(Logger.class); } public boolean shouldSkipField(FieldAttributes fieldAttributes) { // skip simulation of simulated appliance return (fieldAttributes.getName().equals("simulation") && fieldAttributes.getDeclaringClass() == SimulatedAppliance.class) || // skip simulation second data (fieldAttributes.getName().equals("secondData") && fieldAttributes.getDeclaringClass() == Simulation.class) || // skip endTime of energytimestep (fieldAttributes.getName().equals("endTime") && fieldAttributes.getDeclaringClass() == EnergyTimestep.class) || // skip userAppliance, detectionAlgorithmId of appliance state transition ((fieldAttributes.getName().equals("userAppliance") || fieldAttributes.getName().equals("detectionAlgorithmId")) && fieldAttributes.getDeclaringClass() == ApplianceStateTransition.class); } }).create().toJson(wrapper); response.getWriter().write(dataJS); response.setContentType("application/json"); }