Example usage for com.google.gson GsonBuilder create

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

Introduction

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

Prototype

public Gson create() 

Source Link

Document

Creates a Gson instance based on the current configuration.

Usage

From source file:com.gitblit.tickets.TicketSerializer.java

License:Apache License

public static Gson gson(ExclusionStrategy... strategies) {
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(Date.class, new GmtDateTypeAdapter());
    builder.registerTypeAdapter(Score.class, new ScoreTypeAdapter());
    if (!ArrayUtils.isEmpty(strategies)) {
        builder.setExclusionStrategies(strategies);
    }/*from   w w  w  .  j  a  v  a  2  s.c  om*/
    return builder.create();
}

From source file:com.gitblit.utils.JsonUtils.java

License:Apache License

public static Gson gson(ExclusionStrategy... strategies) {
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(Date.class, new GmtDateTypeAdapter());
    builder.registerTypeAdapter(AccessPermission.class, new AccessPermissionTypeAdapter());
    if (!ArrayUtils.isEmpty(strategies)) {
        builder.setExclusionStrategies(strategies);
    }/*  ww  w  . j ava  2s. co m*/
    return builder.create();
}

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//www .  j av  a 2 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 ww  .  j av  a  2s.  c  o  m*/
 * 
 * @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.francescojo.gsondbg.GsonDebuggable.java

/**
 * Gets a {@code GsonDebuggable} which is created and cached by VM. Json deserialisation is done by
 *
 * @param builder your own {@link com.google.gson.GsonBuilder} instance.
 * @return a {@code GsonDebuggable} instance.
 *//*from ww  w .j av a2 s  .com*/
// TODO: test instance caching
public static GsonDebuggable getInstanceWith(GsonBuilder builder) {
    if (null == GsonDebuggable.instanceFactory) {
        // No equals method on GsonBuilder :(
        if (null != builder && InstanceHolder.INSTANCE.gsonBuilder != builder) {
            InstanceHolder.INSTANCE.gson = builder.create();
        }

        return InstanceHolder.INSTANCE;
    } else {
        try {
            return instanceFactory.call();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

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);//w w w.  j  a v a 2  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.kyriosdata.regras.infraestrutura.Serializador.java

License:Creative Commons License

/**
 * Cria instncia de serializar preparada
 * para realizar converses entre objetos e
 * sequncias de caracters.//from   ww  w .jav  a 2  s . c  o  m
 *
 * <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  .java 2s .c  o  m
    }

    gson = gsonBuilder.create();
}