Example usage for com.google.gson ExclusionStrategy ExclusionStrategy

List of usage examples for com.google.gson ExclusionStrategy ExclusionStrategy

Introduction

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

Prototype

ExclusionStrategy

Source Link

Usage

From source file:br.edu.ifpe.garanhuns.pos.sysadvogacia.controladores.ControladorClienteServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from w w w  .  ja  va2s .co m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String userPath = request.getServletPath();
    NegocioCliente negocioCliente = new NegocioCliente();
    Cliente cliente;

    if (userPath.equals("/SalvarCliente")) {
        cliente = new Cliente();
        if (!request.getParameter("codigo").isEmpty()) {
            cliente.setCodigo(Integer.parseInt(request.getParameter("codigo")));
        } else {
            cliente.setCodigo(0);
        }
        cliente.setNome(request.getParameter("nome"));
        cliente.setCpfCnpj(request.getParameter("cpfCnpj"));
        cliente.setEndereco(request.getParameter("endereco"));
        cliente.setTelefone(request.getParameter("telefone"));

        String json = new Gson().toJson(negocioCliente.salvar(cliente));
        response.getWriter().print(json);

    }

    if (userPath.equals("/ListarClientes")) {
        Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {

            public boolean shouldSkipClass(Class<?> clazz) {
                return (clazz == Processo.class);
            }

            /**
             * Custom field exclusion goes here
             */
            public boolean shouldSkipField(FieldAttributes f) {
                return false;
            }

        })
                /**
                 * Use serializeNulls method if you want To serialize null
                 * values By default, Gson does not serialize null values
                 */
                .serializeNulls().create();

        String json = gson.toJson(negocioCliente.listarClientes());
        response.getWriter().print(json);
    }

    if (userPath.equals("/RemoverCliente")) {
        JsonObject jsonObject = new JsonObject();
        try {
            String id = request.getParameter("id");
            cliente = negocioCliente.clientePorCodigo(Integer.parseInt(id));
            negocioCliente.remover(cliente);
            jsonObject.addProperty("success", "true");
            response.getWriter().print(new Gson().toJson(jsonObject));
        } catch (RemoverClienteComProcessosException e) {
            jsonObject.addProperty("errorMsg", e.mensagem());
            response.getWriter().print(new Gson().toJson(jsonObject));
        }

    }

}

From source file:ca.oson.json.Oson.java

License:Open Source License

public Gson getGson() {
    if (gson == null) {
        GsonBuilder gsonBuilder = new GsonBuilder();

        switch (getDefaultType()) {
        case ALWAYS:
            gsonBuilder.serializeNulls();
            break;
        case NON_NULL:
            break;
        case NON_EMPTY:
            break;
        case DEFAULT:
            gsonBuilder.serializeNulls();
            break;
        default:/* w ww  .j a  va 2  s.  com*/
            gsonBuilder.serializeNulls();
            break;
        }

        switch (getFieldNaming()) {
        case FIELD: // original field name: someField_name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY);
            break;
        case LOWER: // somefield_name -> some_field_name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
            break;
        case UPPER: //SOMEFIELD_NAME -> SomeFieldName
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE);
            break;
        case CAMELCASE: // someFieldName
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY);
            break;
        case UPPER_CAMELCASE: // SomeFieldName
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE);
            break;
        case UNDERSCORE_CAMELCASE: // some_Field_Name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
            break;
        case UNDERSCORE_UPPER_CAMELCASE: // Some_Field_Name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
            break;
        case UNDERSCORE_LOWER: // some_field_name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
            break;
        case UNDERSCORE_UPPER: // SOME_FIELD_NAME
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
            break;
        case SPACE_CAMELCASE: // some Field Name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES);
            break;
        case SPACE_UPPER_CAMELCASE: // Some Field Name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES);
            break;
        case SPACE_LOWER: // some field name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES);
            break;
        case SPACE_UPPER: // SOME FIELD NAME
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES);
            break;
        case DASH_CAMELCASE: // some-Field-Name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES);
            break;
        case DASH_UPPER_CAMELCASE: // Some-Field-Name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES);
            break;
        case DASH_LOWER: // some-field-name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES);
            break;
        case DASH_UPPER: // SOME-FIELD-NAME
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES);
            break;
        default:
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY);
            break;
        }

        if (getPrettyPrinting() && getIndentation() > 0) {
            gsonBuilder.setPrettyPrinting();
        }

        gsonBuilder.setDateFormat(options.getSimpleDateFormat());

        Set<FieldMapper> mappers = getFieldMappers();
        Map<Class, ClassMapper> classMappers = getClassMappers();
        List<ExclusionStrategy> strategies = new ArrayList<>();
        if (mappers != null) {
            gsonBuilder.setFieldNamingStrategy(new FieldNamingStrategy() {
                @Override
                public String translateName(Field f) {
                    String fieldName = f.getName();
                    String serializedName = java2Json(f);
                    if (!fieldName.equalsIgnoreCase(serializedName)) {
                        // if null returned, this field is ignored
                        return serializedName;
                    }
                    return json2Java(f);
                }
            });

            for (FieldMapper mapper : mappers) {
                if (mapper.java == null || mapper.json == null || mapper.ignore) {
                    strategies.add(new ExclusionStrategy() {

                        @Override
                        public boolean shouldSkipField(FieldAttributes f) {
                            String name = f.getName();
                            Class cls = f.getClass();

                            if (mapper.java == null) {
                                if (mapper.json.equals(name)) {
                                    if (mapper.getType() == null || cls.equals(mapper.getType())) {
                                        return true;
                                    }
                                }

                            } else if (mapper.json == null || mapper.ignore) {
                                if (mapper.java.equals(name)) {
                                    if (mapper.getType() == null || cls.equals(mapper.getType())) {
                                        return true;
                                    }
                                }

                            }

                            return false;
                        }

                        @Override
                        public boolean shouldSkipClass(Class<?> clazz) {
                            return false;
                        }
                    });
                }
            }
        }

        if (classMappers != null) {
            for (Entry<Class, ClassMapper> entry : classMappers.entrySet()) {
                ClassMapper mapper = entry.getValue();
                if (mapper.getType() == null) {
                    mapper.setType(entry.getKey());
                }
                if (mapper.ignore != null && mapper.ignore) {
                    strategies.add(new ExclusionStrategy() {

                        @Override
                        public boolean shouldSkipField(FieldAttributes f) {
                            return false;
                        }

                        @Override
                        public boolean shouldSkipClass(Class<?> clazz) {
                            if (clazz.equals(mapper.getType())) {
                                return true;
                            }
                            return false;
                        }
                    });
                }
            }

            for (Entry<Class, ClassMapper> entry : classMappers.entrySet()) {
                ClassMapper mapper = entry.getValue();
                if (!mapper.ignore && mapper.constructor != null) {
                    gsonBuilder.registerTypeAdapter(entry.getKey(), mapper.constructor);
                }
            }
        }

        int size = strategies.size();
        if (size > 0) {
            gsonBuilder.setExclusionStrategies(strategies.toArray(new ExclusionStrategy[size]));
        }

        Double version = getVersion();
        if (version != null) {
            gsonBuilder.setVersion(version);
        }

        if (isUseGsonExpose()) {
            gsonBuilder.excludeFieldsWithoutExposeAnnotation();
        }

        if (!DefaultValue.isDefault(getPatterns())) {
            gsonBuilder.setLenient();
        }

        gson = gsonBuilder.create();
    }

    return gson;
}

From source file:ch.devmine.javaparser.utils.GsonFactory.java

License:Open Source License

public static Gson build() {
    GsonBuilder builder = new GsonBuilder();
    builder.addSerializationExclusionStrategy(new ExclusionStrategy() {

        @Override/*from w  w w.  j  ava 2  s . c o m*/
        public boolean shouldSkipField(FieldAttributes f) {
            return f.getAnnotation(GsonTransient.class) != null;
        }

        @Override
        public boolean shouldSkipClass(Class<?> c) {
            return c.getAnnotation(GsonTransient.class) != null;
        }
    });
    return builder.create();
}

From source file:com.appslandia.common.json.GsonProcessor.java

License:Open Source License

public static GsonBuilder newBuilder() {
    GsonBuilder builder = new GsonBuilder();
    builder.setExclusionStrategies(new ExclusionStrategy() {

        @Override//w  w  w.  j  av a  2s. com
        public boolean shouldSkipField(FieldAttributes attrs) {
            return attrs.getAnnotation(NotBind.class) != null;
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }
    });
    builder.registerTypeAdapter(java.util.Date.class, new DateAdapter());
    builder.registerTypeAdapter(java.sql.Date.class, new SqlDateAdapter());
    builder.registerTypeAdapter(java.sql.Time.class, new SqlTimeAdapter());
    builder.registerTypeAdapter(java.sql.Timestamp.class, new SqlDateTimeAdapter());
    return builder;
}

From source file:com.camino.lib.provider.network.ServiceGenerator.java

License:Apache License

/**
 * A factory method to create a service instance with authorization
 *///  w  w w .j  a va2s .co  m
public static <S> S createService(String baseUrl, Class<S> serviceClass, final String authToken) {
    OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder()
            //                .connectionPool(new ConnectionPool(MAX_CONNECTIONS, 5, TimeUnit.MINUTES))
            //                .addInterceptor(new StethoInterceptor())
            //                .sslSocketFactory(SSLConfig.getSSLSocketFactory())
            .readTimeout(READ_TIMEOUT_SEC, TimeUnit.SECONDS);

    if (authToken != null) {
        httpClientBuilder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Request original = chain.request();
                Request.Builder requestBuilder = original.newBuilder()
                        .header("Authorization", "Bearer " + authToken)
                        .method(original.method(), original.body());

                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        });
    }

    OkHttpClient client = httpClientBuilder.build();

    Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
        @Override
        public boolean shouldSkipField(FieldAttributes f) {
            return f.getDeclaringClass().equals(RealmObject.class);
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }
    }).create();

    Retrofit.Builder builder = new Retrofit.Builder().baseUrl(baseUrl)
            .callbackExecutor(Executors.newCachedThreadPool())
            .addConverterFactory(GsonConverterFactory.create(gson));

    Retrofit retrofit = builder.client(client).build();

    return retrofit.create(serviceClass);
}

From source file:com.cloudcontrolled.api.client.json.JsonDeserializer.java

License:Apache License

/**
 * /*  w w  w .  ja v  a  2 s. c  o  m*/
 */
private void initializeGson() {
    gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
        public boolean shouldSkipField(FieldAttributes fieldAttributes) {
            if (fieldAttributes.getName().equalsIgnoreCase("serialVersionUUID")) {
                return true;
            }
            return false;
        }

        public boolean shouldSkipClass(Class<?> arg0) {
            return false;
        }
    }).create();
}

From source file:com.collaide.fileuploader.models.repositorty.RepoItems.java

public RepoItems() {
    gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {

        @Override//  w w w . j  a  va2  s.  c o  m
        public boolean shouldSkipField(FieldAttributes fa) {
            return fa.getName().equals("id") && id == -1;
        }

        @Override
        public boolean shouldSkipClass(Class<?> type) {
            return false;
        }
    }).create();
}

From source file:com.comapi.internal.network.RestClient.java

License:Open Source License

/**
 * Create Gson converter for the service.
 *
 * @return Gson converter./*from   w  ww  .  j  a va  2  s.c om*/
 */
private Gson createGson() {

    GsonBuilder gsonBuilder = new GsonBuilder().disableHtmlEscaping().setLenient().

            addSerializationExclusionStrategy(new ExclusionStrategy() {
                @Override
                public boolean shouldSkipField(FieldAttributes f) {
                    return f.getAnnotation(SerializedName.class) == null;
                }

                @Override
                public boolean shouldSkipClass(Class<?> clazz) {
                    return false;
                }
            });

    return gsonBuilder.create();
}

From source file:com.devbliss.doctest.utils.JSONHelper.java

License:Apache License

/**
 * //  w  ww .ja v a2  s  . c  o m
 * Converts the given POJO and will skip the given fields while doing so.
 * If prettyPrint is true, the output will be nicely formatted.
 * 
 * @param obj
 * @param excludedFields
 * @param prettyPrint
 * @return
 */
public String toJsonAndSkipCertainFields(Object obj, final List<String> excludedFields, boolean prettyPrint) {
    ExclusionStrategy strategy = new ExclusionStrategy() {
        public boolean shouldSkipField(FieldAttributes f) {
            if (excludedFields.contains(f.getName())) {
                return true;
            }

            return false;
        }

        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }
    };

    GsonBuilder builder = new GsonBuilder().addSerializationExclusionStrategy(strategy)
            .addDeserializationExclusionStrategy(strategy);

    if (prettyPrint)
        builder.setPrettyPrinting();

    return builder.create().toJson(obj);
}

From source file:com.events.events.network.Rest.java

License:Apache License

private Gson getConvertedGson() {
    return new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
        @Override/*from w  ww.j a v  a 2  s .  c  o  m*/
        public boolean shouldSkipField(FieldAttributes f) {
            return true;
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }
    }).create();
}