Example usage for com.google.gson GsonBuilder excludeFieldsWithoutExposeAnnotation

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

Introduction

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

Prototype

public GsonBuilder excludeFieldsWithoutExposeAnnotation() 

Source Link

Document

Configures Gson to exclude all fields from consideration for serialization or deserialization that do not have the com.google.gson.annotations.Expose annotation.

Usage

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://from  w  ww. ja v  a  2 s  . c  o m
            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:ca.ualberta.cmput301w14t08.geochan.helpers.GsonHelper.java

License:Apache License

private GsonHelper() {
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(Comment.class, new CommentJsonConverter());
    builder.registerTypeAdapter(ThreadComment.class, new ThreadCommentJsonConverter());
    builder.registerTypeAdapter(Bitmap.class, new BitmapJsonConverter());
    builder.registerTypeAdapter(Location.class, new LocationJsonConverter());
    onlineGson = builder.create();/*from www  . ja va 2 s .  com*/
    builder = new GsonBuilder();
    builder.registerTypeAdapter(Comment.class, new CommentOfflineJsonConverter());
    builder.registerTypeAdapter(ThreadComment.class, new ThreadCommentOfflineJsonConverter());
    builder.registerTypeAdapter(Location.class, new LocationJsonConverter());
    offlineGson = builder.create();
    builder = new GsonBuilder();
    exposeGson = builder.excludeFieldsWithoutExposeAnnotation().create();
}

From source file:ch.uzh.supersede.feedbacklibrary.FeedbackActivity.java

License:Apache License

public void sendButtonClicked(View view) {
    if (baseURL != null && language != null) {
        // The mechanism models are updated with the view values
        for (MechanismView mechanismView : allMechanismViews) {
            mechanismView.updateModel();
        }/*from  w w  w . j  a  v  a 2s.c o  m*/

        final ArrayList<String> messages = new ArrayList<>();
        if (validateInput(allMechanisms, messages)) {
            if (fbAPI == null) {
                Retrofit rtf = new Retrofit.Builder().baseUrl(baseURL)
                        .addConverterFactory(GsonConverterFactory.create()).build();
                fbAPI = rtf.create(feedbackAPI.class);
            }

            Call<ResponseBody> checkUpAndRunning = fbAPI.pingRepository();
            if (checkUpAndRunning != null) {
                checkUpAndRunning.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Log.e(TAG, "Failed to ping the server. onFailure method called", t);
                        DialogUtils
                                .showInformationDialog(FeedbackActivity.this,
                                        new String[] { getResources()
                                                .getString(R.string.supersede_feedbacklibrary_error_text) },
                                        true);
                    }

                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        if (response.code() == 200) {
                            Feedback feedback = new Feedback(allMechanisms);
                            feedback.setTitle(getResources().getString(
                                    R.string.supersede_feedbacklibrary_feedback_title_text,
                                    System.currentTimeMillis()));
                            feedback.setApplicationId(orchestratorConfiguration.getId());
                            feedback.setConfigurationId(activeConfiguration.getId());
                            feedback.setLanguage(language);
                            feedback.setUserIdentification(Settings.Secure.getString(getContentResolver(),
                                    Settings.Secure.ANDROID_ID));

                            // The JSON string of the feedback
                            GsonBuilder builder = new GsonBuilder();
                            builder.excludeFieldsWithoutExposeAnnotation();
                            builder.serializeNulls();
                            Gson gson = builder.create();
                            Type feedbackType = new TypeToken<Feedback>() {
                            }.getType();
                            String feedbackJsonString = gson.toJson(feedback, feedbackType);
                            RequestBody feedbackJSONPart = RequestBody
                                    .create(MediaType.parse("multipart/form-data"), feedbackJsonString);

                            Map<String, RequestBody> files = new HashMap<>();
                            // Audio multipart
                            List<AudioFeedback> audioFeedbackList = feedback.getAudioFeedbacks();
                            if (audioFeedbackList != null) {
                                for (int pos = 0; pos < audioFeedbackList.size(); ++pos) {
                                    RequestBody requestBody = createRequestBody(
                                            new File(audioFeedbackList.get(pos).getAudioPath()));
                                    String fileName = audioFeedbackList.get(pos).getFileName();
                                    String key = String.format("%1$s\"; filename=\"%2$s",
                                            audioFeedbackList.get(pos).getPartString() + String.valueOf(pos),
                                            fileName);
                                    files.put(key, requestBody);
                                }
                            }
                            // Screenshots multipart
                            List<ScreenshotFeedback> screenshotFeedbackList = feedback.getScreenshotFeedbacks();
                            if (screenshotFeedbackList != null) {
                                for (int pos = 0; pos < screenshotFeedbackList.size(); ++pos) {
                                    RequestBody requestBody = createRequestBody(
                                            new File(screenshotFeedbackList.get(pos).getImagePath()));
                                    String fileName = screenshotFeedbackList.get(pos).getFileName();
                                    String key = String.format("%1$s\"; filename=\"%2$s",
                                            screenshotFeedbackList.get(pos).getPartString()
                                                    + String.valueOf(pos),
                                            fileName);
                                    files.put(key, requestBody);
                                }
                            }

                            // Send the feedback
                            Call<JsonObject> result = fbAPI.createFeedbackVariant(language,
                                    feedback.getApplicationId(), feedbackJSONPart, files);
                            if (result != null) {
                                result.enqueue(new Callback<JsonObject>() {
                                    @Override
                                    public void onFailure(Call<JsonObject> call, Throwable t) {
                                        Log.e(TAG, "Failed to send the feedback. onFailure method called", t);
                                        DialogUtils.showInformationDialog(FeedbackActivity.this,
                                                new String[] { getResources().getString(
                                                        R.string.supersede_feedbacklibrary_error_text) },
                                                true);
                                    }

                                    @Override
                                    public void onResponse(Call<JsonObject> call,
                                            Response<JsonObject> response) {
                                        if (response.code() == 201) {
                                            Log.i(TAG, "Feedback successfully sent");
                                            Toast toast = Toast.makeText(getApplicationContext(),
                                                    getResources().getString(
                                                            R.string.supersede_feedbacklibrary_success_text),
                                                    Toast.LENGTH_SHORT);
                                            toast.show();
                                        } else {
                                            Log.e(TAG, "Failed to send the feedback. Response code == "
                                                    + response.code());
                                            DialogUtils.showInformationDialog(FeedbackActivity.this,
                                                    new String[] { getResources().getString(
                                                            R.string.supersede_feedbacklibrary_error_text) },
                                                    true);
                                        }
                                    }
                                });
                            } else {
                                Log.e(TAG, "Failed to send the feebdkack. Call<JsonObject> result is null");
                                DialogUtils.showInformationDialog(FeedbackActivity.this,
                                        new String[] { getResources()
                                                .getString(R.string.supersede_feedbacklibrary_error_text) },
                                        true);
                            }
                        } else {
                            Log.e(TAG, "The server is not up and running. Response code == " + response.code());
                            DialogUtils
                                    .showInformationDialog(FeedbackActivity.this,
                                            new String[] { getResources()
                                                    .getString(R.string.supersede_feedbacklibrary_error_text) },
                                            true);
                        }
                    }
                });
            } else {
                Log.e(TAG, "Failed to ping the server. Call<ResponseBody> checkUpAndRunning result is null");
                DialogUtils.showInformationDialog(FeedbackActivity.this,
                        new String[] {
                                getResources().getString(R.string.supersede_feedbacklibrary_error_text) },
                        true);
            }
        } else {
            Log.v(TAG, "Validation of the mechanism failed");
            DialogUtils.showInformationDialog(this, messages.toArray(new String[messages.size()]), false);
        }
    } else {
        if (baseURL == null) {
            Log.e(TAG, "Failed to send the feedback. baseURL is null");
        } else {
            Log.e(TAG, "Failed to send the feedback. language is null");
        }
        DialogUtils.showInformationDialog(this,
                new String[] { getResources().getString(R.string.supersede_feedbacklibrary_error_text) }, true);
    }
}

From source file:cn.taop.utils.GSONUtils.java

License:Apache License

/**
 * ????? {@code JSON} ?/*from w w w . j a va2 s.  c om*/
 * <p />
 * <strong>???? <code>"{}"</code> ? <code>"[]"</code>
 * </strong>
 * 
 * @param target 
 * @param targetType 
 * @param isSerializeNulls ?? {@code null} 
 * @param version ?
 * @param datePattern ??
 * @param excludesFieldsWithoutExpose ? {@literal @Expose} 
 * @return  {@code JSON} ?
 * @since 1.0
 */
public static String toJson(Object target, Type targetType, boolean isSerializeNulls, Double version,
        String datePattern, boolean excludesFieldsWithoutExpose) {
    if (target == null)
        return EMPTY_JSON;
    GsonBuilder builder = new GsonBuilder();
    if (isSerializeNulls)
        builder.serializeNulls();
    if (version != null)
        builder.setVersion(version.doubleValue());
    if (StringUtils.isBlank(datePattern))
        datePattern = DEFAULT_DATE_PATTERN;
    builder.setDateFormat(datePattern);
    if (excludesFieldsWithoutExpose)
        builder.excludeFieldsWithoutExposeAnnotation();
    return toJson(target, targetType, builder);
}

From source file:com.arvato.thoroughly.util.CommonUtils.java

License:Open Source License

/**
 * @param whetherExposeAnnotation//  w  ww  .j av a 2s  .  c  o  m
 * @param dateFormat
 * @return Gson instance
 */
public static Gson getGsonByBuilder(boolean whetherExposeAnnotation, String dateFormat) {
    GsonBuilder gsonBuilder = new GsonBuilder();
    if (whetherExposeAnnotation) {
        //Export only entity with @Expose annotation properties
        gsonBuilder.excludeFieldsWithoutExposeAnnotation();
    }

    gsonBuilder.enableComplexMapKeySerialization();

    if (StringUtils.isEmpty(dateFormat)) {
        dateFormat = "yyyy-MM-dd HH:mm:ss";
    }
    gsonBuilder.setDateFormat(dateFormat);//.serializeNulls()
    gsonBuilder.setVersion(1.0);

    return gsonBuilder.create();
}

From source file:com.avatarproject.core.storage.Serializer.java

License:Open Source License

/**
 * Gets the GSON instance for serializing
 * @return//  ww w  .java2  s.  c  o  m
 */
private static Gson getGson() {
    GsonBuilder builder = new GsonBuilder();
    builder.setVersion(version);
    builder.serializeNulls();
    builder.setPrettyPrinting();
    builder.enableComplexMapKeySerialization();
    builder.excludeFieldsWithoutExposeAnnotation();
    return builder.create();
}

From source file:com.company.flightbooking.controller.AdminPageController.java

@RequestMapping(value = "/search/usernameoremail", produces = "application/json; charset=utf-8")
public @ResponseBody String searchByUsernameOrEmail(@RequestParam(name = "searchValue") String searchValue) {
    List<AccountEntity> resultList = accountRepository
            .findByUsernameStartingWithOrEmailStartingWith(searchValue, searchValue);
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.excludeFieldsWithoutExposeAnnotation().create();
    return gson.toJson(resultList);
}

From source file:com.company.flightbooking.controller.AdminPageController.java

@RequestMapping(value = "/search/customerbyidentitycode", produces = "application/json")
public @ResponseBody String searchCusByIdentityCode(@RequestParam(name = "searchValue") String searchValue) {

    CustomerEntity result = customerRepository.findByIdentityCode(searchValue);

    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.excludeFieldsWithoutExposeAnnotation().create();
    return gson.toJson(result);
}

From source file:com.framework.util.JSONUtil.java

License:Apache License

/**
 * ????? {@code JSON} ?//from   w ww  .j a v  a2  s  .  c om
 * <p />
 * <strong>???? <code>"{}"</code> ? <code>"[]"</code>
 * </strong>
 * 
 * @param target 
 * @param targetType 
 * @param isSerializeNulls ?? {@code null} 
 * @param version ?
 * @param datePattern ??
 * @param excludesFieldsWithoutExpose ? {@literal @Expose} 
 * @return  {@code JSON} ?
 * @since 1.0
 */
public static String toJson(Object target, Type targetType, boolean isSerializeNulls, Double version,
        String datePattern, boolean excludesFieldsWithoutExpose) {
    if (target == null)
        return EMPTY_JSON;
    GsonBuilder builder = new GsonBuilder();
    if (isSerializeNulls)
        builder.serializeNulls();
    if (version != null)
        builder.setVersion(version.doubleValue());
    if (Tools.isEmpty(datePattern))
        datePattern = DEFAULT_DATE_PATTERN;
    builder.setDateFormat(datePattern);
    if (excludesFieldsWithoutExpose)
        builder.excludeFieldsWithoutExposeAnnotation();
    return toJson(target, targetType, builder);
}

From source file:com.goplace.service.generic.implementation.ViewServiceGenImpl.java

License:Open Source License

@Override
public String get(Integer id) throws Exception {
    String data = null;/*from  w  w  w . j  ava 2  s.c  o  m*/
    try {
        oConnection.setAutoCommit(false);
        BeanGenImpl oGenericBean = (BeanGenImpl) Class
                .forName("com.goplace.bean.generic.specific.implementation." + strPojo + "BeanGenSpImpl")
                .newInstance();
        Constructor c = Class
                .forName("com.goplace.dao.generic.specific.implementation." + strPojo + "DaoGenSpImpl")
                .getConstructor(String.class, Connection.class);
        TableDaoGenImpl oGenericDao = (TableDaoGenImpl) c.newInstance(strObjectName, oConnection);
        oGenericBean.setId(id);
        oGenericBean = (BeanGenImpl) (BeanInterface) oGenericDao.get(oGenericBean,
                AppConfigurationHelper.getJsonDepth());
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setDateFormat("dd/MM/yyyy");
        Gson gson = gsonBuilder.excludeFieldsWithoutExposeAnnotation().create();
        data = gson.toJson(oGenericBean);
    } catch (Exception ex) {
        oConnection.rollback();
        ExceptionBooster.boost(new Exception(this.getClass().getName() + ":get ERROR: " + ex.getMessage()));
    } finally {
        oConnection.commit();
    }
    return data;
}