List of usage examples for com.google.gson GsonBuilder serializeNulls
boolean serializeNulls
To view the source code for com.google.gson GsonBuilder serializeNulls.
Click Source Link
From source file:appdev.letsmeet.control.utils.messgeBodyHandlers.GsonMessageBodyHandler.java
private Gson getGson() { if (gson == null) { final GsonBuilder gsonBuilder = new GsonBuilder(); gson = gsonBuilder.serializeNulls().create(); }// ww w . j a v a2 s . c o m return gson; }
From source file:bogdanrechi.lansator.MainWindow.java
License:Open Source License
/** * Load application configuration/*from w w w . j a v a 2 s . co m*/ */ private void loadConfiguration() { GsonBuilder builder = new GsonBuilder(); _mainWindow._gson = builder.serializeNulls().setPrettyPrinting().create(); try { _mainWindow._config = _mainWindow._gson.fromJson( FileContent.readTextFile(Platform.CURRENT_DIRECTORY + "lansator.json"), Configuration.class); } catch (JsonSyntaxException | StringException e) { _mainWindow._log.fatal(e.getMessage()); _mainWindow.displayFatalErrorAndExit("CANNOT_LOAD_CONFIGURATION_FILE"); } }
From source file:bogdanrechi.lansator.updater.App.java
License:Open Source License
public static void main(String[] args) { if (args.length != 1) { Console.println("Usage: LansatorUpdater path_to_lansator.json"); return;/*from w w w. ja v a 2 s . co m*/ } Configuration _config; GsonBuilder builder = new GsonBuilder(); Gson _gson = builder.serializeNulls().setPrettyPrinting().create(); try { _config = _gson.fromJson(FileContent.readTextFile(args[0]), Configuration.class); String imagesFolder = Files.getParent(args[0]) + Platform.FILE_SEPARATOR + "images"; for (ProgramsGroupItem groupItem : _config.programsGroups) { setItemImageFile(imagesFolder, groupItem.imageFile, groupItem); for (ProgramItem programItem : groupItem.programs) { setItemImageFile(imagesFolder, programItem.imageFile, programItem); } } Console.println(_gson.toJson(_config) + "\r\n"); FileContent.writeTextFile(_gson.toJson(_config) + "\r\n", args[0]); } catch (JsonSyntaxException | StringException e) { Console.println(e.getMessage()); } }
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 w w . j a v a 2s . 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: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 a2s. c om 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 . ja va 2s . c o m * <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.android.volley.GsonUtils.java
License:Open Source License
/** * Create the standard {@link com.google.gson.Gson} configuration * * @param serializeNulls//from ww w . j av a 2 s . c o m * whether nulls should be serialized * * @return created gson, never null */ public static final Gson createGson(final boolean serializeNulls) { final GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Date.class, new DateFormatter()); builder.enableComplexMapKeySerialization(); // builder.setFieldNamingPolicy(LOWER_CASE_WITH_UNDERSCORES); if (serializeNulls) builder.serializeNulls(); return builder.create(); // private static final Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().enableComplexMapKeySerialization() // .serializeNulls().setDateFormat("yyyy-MM-dd HH:mm:ss:SSS ") // .setPrettyPrinting().setVersion(1.0).create(); }
From source file:com.antew.redditinpictures.library.json.JsonDeserializer.java
License:Apache License
public static Gson getGson() { if (gson == null) { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Vote.class, new VoteAdapter()); builder.serializeNulls(); gson = builder.create();/*from w ww . jav a2s. co m*/ } return gson; }
From source file:com.avatarproject.core.storage.Serializer.java
License:Open Source License
/** * Gets the GSON instance for serializing * @return/* w w w. ja v a 2 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.azure.webapi.MobileServiceClient.java
License:Open Source License
/** * Constructor for the MobileServiceClient * /*from w w w . j a va2 s .c om*/ * @param appUrl * Mobile Service URL * @param appKey * Mobile Service application key * @param context * The Context where the MobileServiceClient is created */ public MobileServiceClient(URL appUrl, String appKey, Context context) { GsonBuilder gsonBuilder = createMobileServiceGsonBuilder(); gsonBuilder.serializeNulls(); // by default, add null serialization initialize(appUrl, appKey, null, gsonBuilder, context); }