List of usage examples for com.google.gson GsonBuilder registerTypeAdapter
@SuppressWarnings({ "unchecked", "rawtypes" }) public GsonBuilder registerTypeAdapter(Type type, Object typeAdapter)
From source file:com.github.consiliens.harv.run.ToGSON.java
License:Open Source License
/** Constructs a Gson object. **/ public static Gson getGson(final String externalEntityPath) { GsonBuilder gsonBuilder = new GsonBuilder().setPrettyPrinting(); gsonBuilder.registerTypeAdapter(recordClass, new IRequestLogRecordSerializer(externalEntityPath)); gsonBuilder.registerTypeAdapter(recordClass, new IRequestLogRecordDeserializer(externalEntityPath)); return gsonBuilder.create(); }
From source file:com.github.easyjsonapi.core.EasyJsonApi.java
License:Apache License
/** * Convert one {@link JsonApi} object into json api string with resource * objects inside the object/*from w w w. ja va2 s .c om*/ * * @param json * the json api object * @param classes * the classes utilized inside the object * @return the string with json api format * @throws EasyJsonApiException */ public String convertJsonApiToString(JsonApi json, Class<?>... classes) throws EasyJsonApiException { if (Assert.isNull(json)) { return null; } GsonBuilder builder = new GsonBuilder(); builder.setPrettyPrinting(); if (Assert.isNull(this.easyJsonApiConfig)) { setConfigDefault(); } this.serializerJsonApi.setConfig(this.easyJsonApiConfig); this.serializerJsonApi.setClassesUsed(classes); builder.registerTypeAdapter(JsonApi.class, this.serializerJsonApi); String jsonApi = null; try { jsonApi = builder.create().toJson(json); } catch (JsonSyntaxException ex) { throw new EasyJsonApiMalformedJsonException("Problem with json sended!", ex); } return jsonApi; }
From source file:com.github.easyjsonapi.core.EasyJsonApi.java
License:Apache License
/** * Convert one string into {@link JsonApi} object with classes resource * objects inside the object//from w w w.j a va 2 s . c om * * @param json * the json api string * @param classes * the classes utilized inside the object * @return the {@link JsonApi} object * @throws EasyJsonApiException */ public JsonApi convertStringToJsonApi(String json, Class<?>... classes) throws EasyJsonApiException { GsonBuilder builder = new GsonBuilder(); builder.setPrettyPrinting(); if (Assert.isNull(this.easyJsonApiConfig)) { setConfigDefault(); } this.deserializerJsonApi.setConfig(this.easyJsonApiConfig); this.deserializerJsonApi.setClassesUsed(classes); builder.registerTypeAdapter(JsonApi.class, this.deserializerJsonApi); JsonApi jsonApi = null; try { jsonApi = builder.create().fromJson(json, JsonApi.class); } catch (JsonSyntaxException ex) { throw new EasyJsonApiMalformedJsonException("Problem with json sended!", ex); } if (Assert.notNull(jsonApi)) { List<Data> cloneData = jsonApi.getData(); List<Error> cloneError = jsonApi.getErrors(); // Return null when doesn't exist errors and data if (cloneError.isEmpty() && cloneData.isEmpty()) { return null; } else if (!cloneData.isEmpty()) { // Get the first object inside the data and check if has any // attribute instanced Data firstData = cloneData.get(BigDecimal.ZERO.intValue()); // if (Assert.isNull(firstData.getId(), firstData.getType(), firstData.getAttr(), firstData.getRels(), firstData.getLinks())) { // return null; // } if (Assert.isNull(firstData.getId(), firstData.getType(), firstData.getAttr())) { return null; } } else if (!cloneError.isEmpty()) { // Get the first object inside the errors and check if has any // error instanced Error firstError = cloneError.get(BigDecimal.ZERO.intValue()); if (Assert.isNull(firstError.getId(), firstError.getTitle(), firstError.getDetail(), firstError.getCode(), firstError.getMeta(), firstError.getSource(), firstError.getStatus())) { return null; } } } return jsonApi; }
From source file:com.github.kskelm.baringo.BaringoClient.java
License:Open Source License
private RetrofittedImgur create() { client = new OkHttpClient(); client.interceptors().add(new ImgurInterceptor()); HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(Level.BODY); client.interceptors().add(logging);/*from www . j a v a2 s . co m*/ final GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Date.class, new DateAdapter()); // create the various domain-specific // services, giving them a chance to register any Gson // type adapters they're going to need. this.acctSvc = new AccountService(this, gsonBuilder); this.albSvc = new AlbumService(this, gsonBuilder); this.imgSvc = new ImageService(this, gsonBuilder); this.galSvc = new GalleryService(this, gsonBuilder); this.comSvc = new CommentService(this, gsonBuilder); this.cusGalSvc = new CustomGalleryService(this, gsonBuilder); this.topSvc = new TopicService(this, gsonBuilder); this.cnvSvc = new ConversationService(this, gsonBuilder); this.noteSvc = new NotificationService(this, gsonBuilder); this.memeSvc = new MemeService(this, gsonBuilder); this.authSvc = new AuthService(this, clientId, clientSecret); // build the gson object final Gson gson = gsonBuilder.create(); // start up the API client GsonConverterFactory gcf = GsonConverterFactory.create(gson); Retrofit retrofit = new Retrofit.Builder().baseUrl(apiEndpoint).addConverterFactory(gcf).client(client) .build(); return retrofit.create(RetrofittedImgur.class); }
From source file:com.github.kskelm.baringo.CommentService.java
License:Open Source License
protected CommentService(BaringoClient imgurClient, GsonBuilder gsonBuilder) { this.client = imgurClient; gsonBuilder.registerTypeAdapter(CommentListWrapper.class, new CommentListWrapper()); }
From source file:com.github.kyriosdata.regras.infraestrutura.Serializador.java
License:Creative Commons License
/** * Cria instncia de serializar preparada * para realizar converses entre objetos e * sequncias de caracters./*from www . j av a 2 s.c om*/ * * <p>H dois grupos de mtodos principais nessa classe. * Aqueles do tipo {@link #toJson(Pontuacao)}, por exemplo, * cujo argumento o objeto a ser convertido em JSON e, * no sentido inverso, {@link #pontuacao(String)}, que recebe * a sequncia JSON e produz um objeto do tipo {@link Pontuacao}. */ public Serializador() { GsonBuilder gb = new GsonBuilder(); gb.registerTypeAdapter(Valor.class, new ValorSerializer()); gb.registerTypeAdapter(Valor.class, new ValorDeserializer()); gb.registerTypeAdapterFactory(new CustomRegraTypeAdapterFactory()); gson = gb.create(); valorType = new TypeToken<Valor>() { }.getType(); pontuacaoType = new TypeToken<Pontuacao>() { }.getType(); regraExpressaoType = new TypeToken<RegraExpressao>() { }.getType(); regraPontosPorRelato = new TypeToken<RegraPontosPorRelato>() { }.getType(); configuracaoType = new TypeToken<Configuracao>() { }.getType(); relatoType = new TypeToken<Relato>() { }.getType(); relatorioType = new TypeToken<Relatorio>() { }.getType(); }
From source file:com.github.rinde.rinsim.scenario.ScenarioIO.java
License:Apache License
private static Gson initialize() { final GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(ProblemClass.class, adapt(ProblemClassIO.INSTANCE)) .registerTypeHierarchyAdapter(TimeWindowPolicy.class, adapt(TimeWindowHierarchyIO.INSTANCE)) .registerTypeAdapter(Scenario.class, adapt(ScenarioObjIO.INSTANCE)) .registerTypeAdapter(ParcelDTO.class, adapt(ParcelIO.INSTANCE)) .registerTypeAdapter(VehicleDTO.class, adapt(VehicleIO.INSTANCE)) .registerTypeAdapter(Point.class, new PointIO()) .registerTypeAdapter(TimeWindow.class, new TimeWindowIO()) .registerTypeAdapter(Unit.class, adapt(UnitIO.INSTANCE)) .registerTypeAdapter(Supplier.class, adapt(SupplierIO.INSTANCE)) .registerTypeHierarchyAdapter(Graph.class, adapt(GraphIO.INSTANCE)) .registerTypeAdapter(Measure.class, adapt(MeasureIO.INSTANCE)) .registerTypeHierarchyAdapter(Enum.class, adapt(EnumIO.INSTANCE)) .registerTypeAdapter(StopCondition.class, adapt(StopConditionIO.INSTANCE)) .registerTypeAdapter(Class.class, adapt(ClassIO.INSTANCE)) .registerTypeAdapter(ImmutableList.class, adapt(ImmutableListIO.INSTANCE)) .registerTypeAdapter(ImmutableSet.class, adapt(ImmutableSetIO.INSTANCE)) .registerTypeAdapter(ModelBuilder.class, adapt(ModelBuilderIO.INSTANCE)); return builder.create(); }
From source file:com.github.tddts.jet.config.spring.factory.GsonFactoryBean.java
License:Apache License
@Override public void afterPropertiesSet() throws Exception { GsonBuilder gsonBuilder = new GsonBuilder(); if (deserializers != null) { for (Class<?> typeClass : deserializers.keySet()) { gsonBuilder.registerTypeAdapter(typeClass, deserializers.get(typeClass).newInstance()); }//from w w w. ja va 2s .c om } gson = gsonBuilder.create(); }
From source file:com.goforer.base.model.BaseModel.java
License:Apache License
public static GsonBuilder gsonBuilder() { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(ImageMap.class, new ImageMap.ImageMapDeserializer()); builder.registerTypeAdapter(ImageMap.class, new ImageMap.ImageMapSerializer()); builder.serializeNulls();/*from ww w .j a va 2 s . c o m*/ return builder; }
From source file:com.google.api.ads.adwords.keywordoptimizer.api.JsonUtil.java
License:Open Source License
/** * Initializes Gson to convert objects to and from JSON. This method customizes a "plain" Gson by * adding appropriate exclusions strategies / adapters as needed in this project for a "pretty" * output. /*from www.ja v a 2s . c o m*/ */ private static Gson initGson(boolean prettyPrint) { GsonBuilder builder = new GsonBuilder(); // Exclude superclasses. ExclusionStrategy superclassExclusionStrategy = new SuperclassExclusionStrategy(); builder.addDeserializationExclusionStrategy(superclassExclusionStrategy); builder.addSerializationExclusionStrategy(superclassExclusionStrategy); // Exclude underscore fields in client lib objects. ExclusionStrategy underscoreExclusionStrategy = new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes field) { if (field.getName().startsWith("_")) { return true; } return false; } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }; builder.addDeserializationExclusionStrategy(underscoreExclusionStrategy); builder.addSerializationExclusionStrategy(underscoreExclusionStrategy); // Render KeywordCollection as an array of KeywordInfos. builder.registerTypeAdapter(KeywordCollection.class, new JsonSerializer<KeywordCollection>() { @Override public JsonElement serialize(KeywordCollection src, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) { JsonArray out = new JsonArray(); for (KeywordInfo info : src.getListSortedByScore()) { out.add(context.serialize(info)); } return out; } }); // Render Money as a primitive. builder.registerTypeAdapter(Money.class, new JsonSerializer<Money>() { @Override public JsonElement serialize(Money src, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) { JsonElement out = new JsonPrimitive(src.getMicroAmount() / 1000000); return out; } }); // Render Keyword in a simple way. builder.registerTypeAdapter(Keyword.class, new JsonSerializer<Keyword>() { @Override public JsonElement serialize(Keyword src, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) { JsonObject out = new JsonObject(); out.addProperty("text", src.getText()); out.addProperty("matchtype", src.getMatchType().toString()); return out; } }); // Render Throwable in a simple way (for all subclasses). builder.registerTypeHierarchyAdapter(Throwable.class, new JsonSerializer<Throwable>() { @Override public JsonElement serialize(Throwable src, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) { JsonObject out = new JsonObject(); out.addProperty("message", src.getMessage()); out.addProperty("type", src.getClass().getName()); JsonArray stack = new JsonArray(); for (StackTraceElement stackTraceElement : src.getStackTrace()) { JsonObject stackElem = new JsonObject(); stackElem.addProperty("file", stackTraceElement.getFileName()); stackElem.addProperty("line", stackTraceElement.getLineNumber()); stackElem.addProperty("method", stackTraceElement.getMethodName()); stackElem.addProperty("class", stackTraceElement.getClassName()); stack.add(stackElem); } out.add("stack", stack); if (src.getCause() != null) { out.add("cause", context.serialize(src.getCause())); } return out; } }); if (prettyPrint) { builder.setPrettyPrinting(); } return builder.create(); }