Java Code Examples for com.google.gson.GsonBuilder#serializeNulls()

The following examples show how to use com.google.gson.GsonBuilder#serializeNulls() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GsonFactoryBean.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void afterPropertiesSet() {
	GsonBuilder builder = (this.base64EncodeByteArrays ?
			GsonBuilderUtils.gsonBuilderWithBase64EncodedByteArrays() : new GsonBuilder());
	if (this.serializeNulls) {
		builder.serializeNulls();
	}
	if (this.prettyPrinting) {
		builder.setPrettyPrinting();
	}
	if (this.disableHtmlEscaping) {
		builder.disableHtmlEscaping();
	}
	if (this.dateFormatPattern != null) {
		builder.setDateFormat(this.dateFormatPattern);
	}
	this.gson = builder.create();
}
 
Example 2
Source File: GsonFactoryBean.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public void afterPropertiesSet() {
	GsonBuilder builder = (this.base64EncodeByteArrays ?
			GsonBuilderUtils.gsonBuilderWithBase64EncodedByteArrays() : new GsonBuilder());
	if (this.serializeNulls) {
		builder.serializeNulls();
	}
	if (this.prettyPrinting) {
		builder.setPrettyPrinting();
	}
	if (this.disableHtmlEscaping) {
		builder.disableHtmlEscaping();
	}
	if (this.dateFormatPattern != null) {
		builder.setDateFormat(this.dateFormatPattern);
	}
	this.gson = builder.create();
}
 
Example 3
Source File: GsonFactoryBean.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() {
	GsonBuilder builder = (this.base64EncodeByteArrays ?
			GsonBuilderUtils.gsonBuilderWithBase64EncodedByteArrays() : new GsonBuilder());
	if (this.serializeNulls) {
		builder.serializeNulls();
	}
	if (this.prettyPrinting) {
		builder.setPrettyPrinting();
	}
	if (this.disableHtmlEscaping) {
		builder.disableHtmlEscaping();
	}
	if (this.dateFormatPattern != null) {
		builder.setDateFormat(this.dateFormatPattern);
	}
	this.gson = builder.create();
}
 
Example 4
Source File: MainView.java    From HiJson with Apache License 2.0 5 votes vote down vote up
/**
 * 复制节点内容.
 * @param path 节点路径
 * @param isFormat 是否带格式
 * @return 
 */
private String copyNodeContent(String path,boolean isFormat){
    String str = "";
    String arr[] = StringUtils.split(path, String.valueOf(dot));
    System.out.println("Get HashCode : " + tree.hashCode() + " . TabTitle : " + getTabTitle());
    JsonElement obj = (JsonElement)jsonEleTreeMap.get(tree.hashCode());
    if(arr.length>1){
        for(int i =1; i< arr.length; i++){
            int index = Kit.getIndex(arr[i]);
            String key = Kit.getKey(arr[i]);
            if(obj.isJsonPrimitive())break;
            if(index==-1){
                obj = obj.getAsJsonObject().get(key);
            }else{
                obj = obj.getAsJsonObject().getAsJsonArray(key).get(index);
            }
        }
    }
    if(obj!=null && !obj.isJsonNull()){
            GsonBuilder gb = new GsonBuilder();
            if(isFormat) gb.setPrettyPrinting();
            gb.serializeNulls();
            Gson gson = gb.create();
            str = gson.toJson(obj);
    }
    return str;
}
 
Example 5
Source File: GsonFactoryBean.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() {
  GsonBuilder builder = new GsonBuilder();
  if (this.serializeNulls) {
    builder.serializeNulls();
  }
  if (this.prettyPrinting) {
    builder.setPrettyPrinting();
  }
  if (this.disableHtmlEscaping) {
    builder.disableHtmlEscaping();
  }
  if (this.dateFormatPattern != null) {
    builder.setDateFormat(this.dateFormatPattern);
  }
  if (this.typeAdapterFactoryList != null) {
    typeAdapterFactoryList.forEach(builder::registerTypeAdapterFactory);
  }
  if (this.typeAdapterHierarchyFactoryMap != null) {
    typeAdapterHierarchyFactoryMap.forEach(builder::registerTypeHierarchyAdapter);
  }
  if (this.registerJavaTimeConverters) {
    Converters.registerInstant(builder);
    Converters.registerLocalDate(builder);
  }
  this.gson = builder.create();
}
 
Example 6
Source File: ExtDirectGsonBuilderConfigurator.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void configure(final GsonBuilder builder, final GlobalConfiguration configuration) {
  if (configuration.getDebug()) {
    builder.setPrettyPrinting();
  }
  builder.serializeNulls();
  builder.disableHtmlEscaping();

  builder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
}
 
Example 7
Source File: JsonSerializer.java    From mobile-messaging-sdk-android with Apache License 2.0 5 votes vote down vote up
public JsonSerializer(boolean serializeNulls, ObjectAdapter... adapters) {
    GsonBuilder builder = new GsonBuilder();
    if (serializeNulls) {
        builder.serializeNulls();
    }
    if (adapters.length > 0) {
        for (ObjectAdapter adapter : adapters) {
            builder.registerTypeHierarchyAdapter(adapter.getCls(), new CustomTypeAdapter(adapter));
        }
    }
    gson = builder.create();
}
 
Example 8
Source File: MobileServiceClient.java    From azure-mobile-apps-android-client with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a GsonBuilder with custom serializers to use with Microsoft Azure
 * Mobile Services
 *
 * @return
 */
private static GsonBuilder createMobileServiceGsonBuilder() {
    GsonBuilder gsonBuilder = new GsonBuilder();

    // Register custom date serializer/deserializer
    gsonBuilder.registerTypeAdapter(Date.class, new DateSerializer());
    LongSerializer longSerializer = new LongSerializer();
    gsonBuilder.registerTypeAdapter(Long.class, longSerializer);
    gsonBuilder.registerTypeAdapter(long.class, longSerializer);

    gsonBuilder.excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC);
    gsonBuilder.serializeNulls(); // by default, add null serialization

    return gsonBuilder;
}
 
Example 9
Source File: ProximityForestResult.java    From ProximityForest with GNU General Public License v3.0 5 votes vote down vote up
public String exportJSON(String datasetName, int experiment_id) throws Exception {
		String file = "";
		String timestamp = LocalDateTime.now()
			       .format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss_SSS"));		
		
		file = AppContext.output_dir + File.separator + forest_id + timestamp;
		
		File fileObj = new File(file);
		
		fileObj.getParentFile().mkdirs();
		fileObj.createNewFile();		
		
		try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))){		
		
			Gson gson;
			GsonBuilder gb = new GsonBuilder();
			gb.serializeSpecialFloatingPointValues();
			gb.serializeNulls();
			gson = gb.create();
			
//			SerializableResultSet object = new SerializableResultSet(this.forests);
			
			bw.write(gson.toJson(this));
			bw.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
//			bw.close();
		}
					
		return file;
	}
 
Example 10
Source File: HttpUtils.java    From qvod with MIT License 5 votes vote down vote up
private Gson getGson() {
    if (gson == null) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setFieldNamingStrategy(new AnnotateNaming());
        gsonBuilder.serializeNulls();
        gsonBuilder.excludeFieldsWithModifiers(Modifier.TRANSIENT);
        gson = gsonBuilder.create();
    }
    return gson;
}
 
Example 11
Source File: ScriptObjectMirrorSerializer.java    From opentest with MIT License 5 votes vote down vote up
public ScriptObjectMirrorSerializer(boolean serializeNulls) {
    if (this.gson == null) {
        GsonBuilder builder = Factory.getGsonBuilder();

        if (serializeNulls) {
            builder = builder.serializeNulls();
        }

        this.gson = builder
                .registerTypeAdapter(ScriptObjectMirror.class, this)
                .create();
    }
}
 
Example 12
Source File: GsonMessageBodyHandler.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Gson buildSerializer() {
	GsonBuilder builder = new GsonBuilder();
	builder.setDateFormat(API_JSON_DATETIME_PATTERN);
	builder.serializeNulls();
	builder.setExclusionStrategies(JsUtil.GSON_EXCLUSION_STRATEGIES);
	builder.registerTypeAdapter(NoShortcutSerializationWrapper.class, new JsonSerializer<NoShortcutSerializationWrapper<?>>() {

		@Override
		public JsonElement serialize(NoShortcutSerializationWrapper<?> src, Type typeOfSrc, JsonSerializationContext context) {
			return context.serialize(src.getVo());
		}
	});
	return builder.create();
}
 
Example 13
Source File: GsonMessageBodyHandler.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Gson buildShortcutSerializer() {
	GsonBuilder builder = new GsonBuilder();
	builder.setDateFormat(API_JSON_DATETIME_PATTERN);
	builder.serializeNulls();
	builder.setExclusionStrategies(JsUtil.GSON_EXCLUSION_STRATEGIES);
	builder.registerTypeAdapter(NoShortcutSerializationWrapper.class, new JsonSerializer<NoShortcutSerializationWrapper<?>>() {

		@Override
		public JsonElement serialize(NoShortcutSerializationWrapper<?> src, Type typeOfSrc, JsonSerializationContext context) {
			return serializer.toJsonTree(src.getVo()); // use regular serializer
		}
	});
	JsUtil.registerGsonTypeAdapters(builder, JsUtil.GSON_SHORTCUT_SERIALISATIONS);
	return builder.create();
}
 
Example 14
Source File: JSONUtil.java    From fixflow with Apache License 2.0 5 votes vote down vote up
private 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 (StringUtil.isEmpty(datePattern))   
//            datePattern = DEFAULT_DATE_PATTERN;   
        builder.setDateFormat(datePattern);   
        if (excludesFieldsWithoutExpose)   
            builder.excludeFieldsWithoutExposeAnnotation();   
        String result = null;   
        Gson gson = builder.create();   
        try {   
            if (targetType != null) {   
                result = gson.toJson(target, targetType);   
            } else {   
                result = gson.toJson(target);   
            }   
        } catch (Exception ex) {      
            if (target instanceof Collection || target instanceof Iterator   
                    || target instanceof Enumeration || target.getClass().isArray()) {   
                result = EMPTY_JSON_ARRAY;   
            } else  
                result = EMPTY_JSON;   
        }   
        return result;   
    }
 
Example 15
Source File: SimpleJsonManager.java    From lastaflute with Apache License 2.0 4 votes vote down vote up
protected void setupSerializeNullsSettings(GsonBuilder builder, boolean serializeNulls) {
    if (serializeNulls) {
        builder.serializeNulls();
    }
}
 
Example 16
Source File: JsonUtil.java    From AndroidRobot with Apache License 2.0 4 votes vote down vote up
/**
 * 将给定的目标对象根据指定的条件参数转换成 {@code JSON} 格式的字符串。
 * <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} 格式的字符串。
 */
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 (isEmpty(datePattern)) {
        datePattern = DEFAULT_DATE_PATTERN;
    }

    builder.setDateFormat(datePattern);
    if (excludesFieldsWithoutExpose) {
        builder.excludeFieldsWithoutExposeAnnotation();
    }

    String result = "";

    Gson gson = builder.create();

    try {
        if (targetType != null) {
            result = gson.toJson(target, targetType);
        } else {
            result = gson.toJson(target);
        }
    } catch (Exception ex) {
        if (target instanceof Collection || target instanceof Iterator
            || target instanceof Enumeration || target.getClass().isArray()) {
            result = EMPTY_JSON_ARRAY;
        } else {
            result = EMPTY_JSON;
        }

    }

    return result;
}
 
Example 17
Source File: GsonHelper.java    From sumk with Apache License 2.0 4 votes vote down vote up
public static GsonBuilder builder(String module) {
	if (module == null || module.isEmpty()) {
		module = "sumk";
	}

	DateTimeTypeAdapter da = new DateTimeTypeAdapter();
	String format = AppInfo.get(module + ".gson.date.format");
	if (StringUtil.isNotEmpty(format)) {
		da.setDateFormat(format);
	}

	GsonBuilder gb = new GsonBuilder().registerTypeAdapter(Date.class, da);

	if (AppInfo.getBoolean(module + ".gson.disableHtmlEscaping", false)) {
		gb.disableHtmlEscaping();
	}
	if (AppInfo.getBoolean(module + ".gson.shownull", false)) {
		gb.serializeNulls();
	}
	if (AppInfo.getBoolean(module + ".gson.disableInnerClassSerialization", false)) {
		gb.disableInnerClassSerialization();
	}
	if (AppInfo.getBoolean(module + ".gson.generateNonExecutableJson", false)) {
		gb.generateNonExecutableJson();
	}
	if (AppInfo.getBoolean(module + ".gson.serializeSpecialFloatingPointValues", false)) {
		gb.serializeSpecialFloatingPointValues();
	}

	if (AppInfo.getBoolean(module + ".gson.longSerialize2String", false)) {
		gb.setLongSerializationPolicy(LongSerializationPolicy.STRING);
	}

	if (AppInfo.getBoolean(module + ".gson.prettyPrinting", false)) {
		gb.setPrettyPrinting();
	}
	if (AppInfo.getBoolean(module + ".gson.date.adaper", true)) {
		DateAdapters.registerAll(gb);
	}
	return gb;
}
 
Example 18
Source File: GsonUtils.java    From DevUtils with Apache License 2.0 4 votes vote down vote up
/**
 * 创建 GsonBuilder
 * @param serializeNulls 是否序列化 null 值
 * @return {@link GsonBuilder}
 */
public static GsonBuilder createGson(final boolean serializeNulls) {
    GsonBuilder builder = new GsonBuilder();
    if (serializeNulls) builder.serializeNulls();
    return builder;
}
 
Example 19
Source File: PanguAnalyeMain.java    From DevUtils with Apache License 2.0 4 votes vote down vote up
/**
 * 创建 GsonBuilder
 * @param serializeNulls 是否序列化null值
 * @return {@link GsonBuilder}
 */
private static GsonBuilder createGson(final boolean serializeNulls) {
    final GsonBuilder builder = new GsonBuilder();
    if (serializeNulls) builder.serializeNulls();
    return builder;
}
 
Example 20
Source File: GsonFactory.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
private static Gson create(
      Set<TypeAdapterFactory> typeAdapterFactories,
      Set<TypeAdapter<?>> typeAdapters,
      Set<JsonSerializer<?>> serializers,
      Set<JsonDeserializer<?>> deserializers,
      boolean serializeNulls
) {
   IrisObjectTypeAdapterFactory.install();

   GsonBuilder builder = new GsonBuilder();
   if (serializeNulls) {
      builder.serializeNulls();
   }

   builder.disableHtmlEscaping();
   builder.registerTypeAdapter(Date.class, new DateTypeAdapter());

   if(typeAdapterFactories != null) {
      for(TypeAdapterFactory factory : typeAdapterFactories) {
         builder.registerTypeAdapterFactory(factory);
      }
   }

   if(typeAdapters != null) {
      for(TypeAdapter<?> adapter : typeAdapters) {
         builder.registerTypeAdapter(extractType(adapter), adapter);
      }
   }

   if(serializers != null) {
      for(JsonSerializer<?> serializer : serializers) {
         builder.registerTypeAdapter(extractType(serializer, JsonSerializer.class), serializer);
      }
   }

   if(deserializers != null) {
      for(JsonDeserializer<?> deserializer : deserializers) {
         builder.registerTypeAdapter(extractType(deserializer, JsonDeserializer.class), deserializer);
      }
   }

   return builder.create();
}