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

The following examples show how to use com.google.gson.GsonBuilder#setDateFormat() . 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: XGsonBuilder.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
public static Gson instance() {
	if (null == INSTANCE) {
		synchronized (XGsonBuilder.class) {
			if (null == INSTANCE) {
				GsonBuilder gson = new GsonBuilder();
				gson.setDateFormat(DateTools.format_yyyyMMddHHmmss);
				gson.registerTypeAdapter(Integer.class, new IntegerDeserializer());
				gson.registerTypeAdapter(Double.class, new DoubleDeserializer());
				gson.registerTypeAdapter(Float.class, new FloatDeserializer());
				gson.registerTypeAdapter(Long.class, new LongDeserializer());
				gson.registerTypeAdapter(Date.class, new DateDeserializer());
				gson.registerTypeAdapter(Date.class, new DateSerializer());
				INSTANCE = gson.setPrettyPrinting().create();
			}
		}
	}
	return INSTANCE;
}
 
Example 3
Source File: GsonFactoryBean.java    From lams with GNU General Public License v2.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: EventServlet.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public EventServlet(LeshanServer server, int securePort) {
    this.server = server;
    server.getClientRegistry().addListener(this.clientRegistryListener);
    server.getObservationRegistry().addListener(this.observationRegistryListener);

    // add an interceptor to each endpoint to trace all CoAP messages
    coapMessageTracer = new CoapMessageTracer(server.getClientRegistry());
    for (Endpoint endpoint : server.getCoapServer().getEndpoints()) {
        endpoint.addInterceptor(coapMessageTracer);
    }

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeHierarchyAdapter(Client.class, new ClientSerializer(securePort));
    gsonBuilder.registerTypeHierarchyAdapter(LwM2mNode.class, new LwM2mNodeSerializer());
    gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
    this.gson = gsonBuilder.create();
}
 
Example 5
Source File: WGsonConvert.java    From wES with MIT License 6 votes vote down vote up
/**
 * 构建通用GsonBuilder, 封装初始化工作
 *
 * @return
 */
public static GsonBuilder getGsonBuilder(boolean prettyPrinting) {
	GsonBuilder gb = new GsonBuilder();
	gb.setDateFormat("yyyy-MM-dd HH:mm:ss:mss");
	gb.setExclusionStrategies(new ExclusionStrategy() {
		@Override
		public boolean shouldSkipField(FieldAttributes f) {
			return f.getAnnotation(WJsonExclued.class) != null;
		}

		@Override
		public boolean shouldSkipClass(Class<?> clazz) {
			return clazz.getAnnotation(WJsonExclued.class) != null;
		}
	});
	if (prettyPrinting)
		gb.setPrettyPrinting();
	return gb;
}
 
Example 6
Source File: MainActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
private static List<Song> parseJson(InputStream rawJsonStream) {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setDateFormat("yyyy-MM-dd'T'hh:MM:ss");
    Gson gson = gsonBuilder.create();
    Type collectionType = new TypeToken<List<Song>>() {
    }.getType();
    List<Song> songs = gson.fromJson(new InputStreamReader(rawJsonStream), collectionType);
    return songs;
}
 
Example 7
Source File: JSONUtil.java    From FoxBPM 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 8
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 9
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 10
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 11
Source File: DataSerializer.java    From development with Apache License 2.0 5 votes vote down vote up
public DataSerializer(Class<?> clazz) {
    this.clazz = clazz;

    GsonBuilder builder = new GsonBuilder();
    builder.setDateFormat(FORMAT_DATE);
    this.gson = builder.create();
}
 
Example 12
Source File: GsonMessageProvider.java    From development with Apache License 2.0 5 votes vote down vote up
@Override
public void writeTo(Representation rep, Class<?> type, Type genericType,
        Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, Object> httpHeaders,
        OutputStream entityStream) throws IOException,
        WebApplicationException {

    OutputStreamWriter writer = new OutputStreamWriter(entityStream,
            CommonParams.CHARSET);

    try {
        GsonBuilder builder = new GsonBuilder();
        builder.setDateFormat(CommonParams.FORMAT_DATE);

        if (rep.getVersion() != null) {
            builder.setVersion(rep.getVersion().intValue());
        }

        Gson gson = builder.create();
        gson.toJson(rep, genericType, writer);

    } catch (JsonSyntaxException e) {
        throw WebException.internalServerError()
                .message(CommonParams.ERROR_JSON_FORMAT).build();
    } finally {
        writer.close();
    }

}
 
Example 13
Source File: ApiServlet.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public ApiServlet(LwM2mServer server, int securePort) {
    this.server = server;

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeHierarchyAdapter(Client.class, new ClientSerializer(securePort));
    gsonBuilder.registerTypeHierarchyAdapter(LwM2mResponse.class, new ResponseSerializer());
    gsonBuilder.registerTypeHierarchyAdapter(LwM2mNode.class, new LwM2mNodeSerializer());
    gsonBuilder.registerTypeHierarchyAdapter(LwM2mNode.class, new LwM2mNodeDeserializer());
    gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
    this.gson = gsonBuilder.create();
}
 
Example 14
Source File: JsonUtil.java    From go-plugins with Apache License 2.0 4 votes vote down vote up
public static String toJsonString(Object object) {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    return gsonBuilder.create().toJson(object);
}
 
Example 15
Source File: GsonJsonEngine.java    From lastaflute with Apache License 2.0 4 votes vote down vote up
protected void registerUtilDateFormat(GsonBuilder builder) {
    builder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss"); // same as local date-time
}
 
Example 16
Source File: HttpKit.java    From UPMiss with GNU General Public License v3.0 4 votes vote down vote up
public static GsonBuilder getRspGsonBuilder() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setExclusionStrategies(new SpecificClassExclusionStrategy(null, BaseModel.class));
    gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    return gsonBuilder;
}
 
Example 17
Source File: HttpKit.java    From UPMiss with GNU General Public License v3.0 4 votes vote down vote up
public static GsonBuilder getGsonBuilder() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setExclusionStrategies(new SpecificClassExclusionStrategy(null, BaseModel.class));
    gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    return gsonBuilder;
}
 
Example 18
Source File: ProductModel.java    From UPMiss with GNU General Public License v3.0 4 votes vote down vote up
static GsonBuilder getRspGsonBuilder() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    return gsonBuilder;
}
 
Example 19
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 20
Source File: JsonHandler.java    From wings with Apache License 2.0 4 votes vote down vote up
public static Gson createDataGson() {
  GsonBuilder gson = new GsonBuilder();
  gson.setDateFormat("yyyy-MM-dd");
  return gson.disableHtmlEscaping().create();
  //return gson.disableHtmlEscaping().setPrettyPrinting().create();
}