Java Code Examples for com.alibaba.fastjson.JSON#toJSONStringWithDateFormat()

The following examples show how to use com.alibaba.fastjson.JSON#toJSONStringWithDateFormat() . 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: FastJsonUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenSerializeConfig_whenJavaObject_thanJsonCorrect() {
    NameFilter formatName = new NameFilter() {
        public String process(Object object, String name, Object value) {
            return name.toLowerCase()
                .replace(" ", "_");
        }
    };
    SerializeConfig.getGlobalInstance()
        .addFilter(Person.class, formatName);
    String jsonOutput = JSON.toJSONStringWithDateFormat(listOfPersons, "yyyy-MM-dd");
    assertEquals(jsonOutput, "[{\"first_name\":\"Doe\",\"last_name\":\"John\"," + "\"date_of_birth\":\"2016-07-24\"},{\"first_name\":\"Doe\",\"last_name\":" + "\"Janette\",\"date_of_birth\":\"2016-07-24\"}]");
    // resetting custom serializer
    SerializeConfig.getGlobalInstance()
        .put(Person.class, null);
}
 
Example 2
Source File: UnitResponse.java    From xian with Apache License 2.0 5 votes vote down vote up
/**
 * Standard json formation without data lost.
 */
public String toJSONString() {
    if (context.isPretty()) {
        return JSON.toJSONStringWithDateFormat(this, Constant.DATE_SERIALIZE_FORMAT, SerializerFeature.PrettyFormat);
    } else {
        return JSONObject.toJSONStringWithDateFormat(this, Constant.DATE_SERIALIZE_FORMAT);
    }
}
 
Example 3
Source File: AliSerializer.java    From Thunder with Apache License 2.0 5 votes vote down vote up
public static <T> String toJson(T object) {
    if (object == null) {
        throw new SerializerException("Object is null");
    }

    return JSON.toJSONStringWithDateFormat(object, ThunderConstant.DATE_FORMAT, SerializerFeature.WriteClassName);
}
 
Example 4
Source File: JsonUtil.java    From utils with Apache License 2.0 5 votes vote down vote up
/**
 * 对象转换为json,可以带上date的格式化.
 *
 * @param object
 * @param dateFormat
 * @return java.lang.String
 */
public static String beanToJson(Object object, String dateFormat) {
    if (Objects.isNull(dateFormat) || "".equals(dateFormat)) {
        return JSON.toJSONString(object);
    }
    return JSON.toJSONStringWithDateFormat(object, dateFormat);

}
 
Example 5
Source File: JSONUtils.java    From yyblog with MIT License 5 votes vote down vote up
/**
 * Bean对象转JSON
 * 
 * @param object
 * @param dataFormatString
 * @return
 */
public static String beanToJson(Object object, String dataFormatString) {
    if (object != null) {
        if (StringUtils.isEmpty(dataFormatString)) {
            return JSONObject.toJSONString(object);
        }
        return JSON.toJSONStringWithDateFormat(object, dataFormatString);
    } else {
        return null;
    }
}
 
Example 6
Source File: DefaultSliceParser.java    From dataprocessor with MIT License 5 votes vote down vote up
@Override
public String serialize(Set<Slice<S>> slices) {
    if (slices == null || slices.size() <= 0) {
        throw new IllegalArgumentException("slices切片集不能为空");
    }
    String typeName = getType(slices.iterator().next());
    return typeName + TYPE_SEPARATOR + JSON.toJSONStringWithDateFormat(slices, "yyyy-MM-dd'T'HH:mm:ss.SSS");
}
 
Example 7
Source File: Node.java    From xian with Apache License 2.0 5 votes vote down vote up
@Override
public UnitResponse send(UnitRequest request) {
    String ssid = IdManager.nextSsid();
    request.getContext().setSsid(ssid);
    fillRequestContext(request.getContext());
    UnitResponse unitResponse = UnitResponse.create(true);
    final CountDownLatch latch = new CountDownLatch(1);
    NotifyHandler handler = new NotifyHandler() {
        @Override
        public void handle(UnitResponse output) {
            UnitResponse.copy(output, output);
            latch.countDown();
        }
    };
    handleMap.put(ssid, handler);
    String payload = JSON.toJSONStringWithDateFormat(request, Constant.DATE_SERIALIZE_FORMAT);
    publisher.p2pPublish(request.getContext().getDestinationNodeId(), payload);
    try {
        if (!latch.await(Constant.UNIT_DEFAULT_TIME_OUT_IN_MILLI, TimeUnit.MILLISECONDS)) {
            handler.setTimeout(true);
            return UnitResponse.createError(Group.CODE_TIME_OUT, null, "Response time out!")
                    .setContext(UnitResponse.Context.create().setSsid(ssid));
        }
    } catch (InterruptedException e) {
        return UnitResponse.createException(e);
    }
    return unitResponse;
}
 
Example 8
Source File: Node.java    From xian with Apache License 2.0 5 votes vote down vote up
@Override
public void send(UnitRequest request, NotifyHandler handler) {
    String ssid = IdManager.nextSsid();
    request.getContext().setSsid(ssid);
    fillRequestContext(request.getContext());
    String payload = JSON.toJSONStringWithDateFormat(request, Constant.DATE_SERIALIZE_FORMAT);
    handleMap.put(ssid, handler);
    publisher.p2pPublish(request.getContext().getDestinationNodeId(), payload);
}
 
Example 9
Source File: UnitResponse.java    From xian with Apache License 2.0 5 votes vote down vote up
/**
 * No matter context pretty attribute is true or not, this method formats the json string you want.
 *
 * @param pretty pretty or not.
 * @return formatted json string.
 */
public String toVoJSONString(boolean pretty) {
    if (pretty) {
        return JSON.toJSONStringWithDateFormat(toVoJSONObject(), Constant.DATE_SERIALIZE_FORMAT, SerializerFeature.PrettyFormat);
    } else {
        return JSONObject.toJSONStringWithDateFormat(toVoJSONObject(), Constant.DATE_SERIALIZE_FORMAT);
    }
}
 
Example 10
Source File: UnitResponse.java    From xian with Apache License 2.0 5 votes vote down vote up
/**
 * Our api gateway uses this method instead of {@link #toJSONString()} {@link #toString()} to produce a desensitized output VO json string.
 * For detail, see the return description.
 *
 * @return json string with sensitive properties(the context property) hidden.
 */
public String toVoJSONString() {
    if (context.isPretty()) {
        return JSON.toJSONStringWithDateFormat(toVoJSONObject(), Constant.DATE_SERIALIZE_FORMAT, SerializerFeature.PrettyFormat);
    } else {
        return JSONObject.toJSONStringWithDateFormat(toVoJSONObject(), Constant.DATE_SERIALIZE_FORMAT);
    }
}
 
Example 11
Source File: DefaultSliceParser.java    From dataprocessor with MIT License 4 votes vote down vote up
@Override
public String serialize(Slice<S> slice) {
    String typeName = getType(slice);
    return typeName + TYPE_SEPARATOR + JSON.toJSONStringWithDateFormat(slice, "yyyy-MM-dd'T'HH:mm:ss.SSS");
}
 
Example 12
Source File: LogAspectOld.java    From seed with Apache License 2.0 4 votes vote down vote up
public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
    Object respData;
    long startTime = System.currentTimeMillis();
    String className = joinPoint.getTarget().getClass().getSimpleName(); //获取类名(这里只切面了Controller类)
    String methodName = joinPoint.getSignature().getName();              //获取方法名
    String methodInfo = className + "." + methodName;                    //组织类名.方法名
    //Object[] objs = joinPoint.getArgs();                               //获取方法参数
    //String paramInfo = com.alibaba.fastjson.JSON.toJSONString(args);
    /*
    if(RouterController.class.getSimpleName().equals(className)){
        return joinPoint.proceed();
    }
    */
    /*
     * 打印Controller入参
     * 1.也可以使用@Resource注入private HttpServletRequest request;再加上setRequest()即可
     *   当使用@Resource注入HttpServletRequest时,在JUnit中通过new ClassPathXmlApplicationContext("applicationContext.xml")加载Spring时会报告下面的异常
     *   org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.servlet.http.HttpServletRequest] found for dependency
     *   所以这里通过RequestContextHolder来获取HttpServletRequest
     * 2.当上传文件时,由于表单设置了enctype="multipart/form-data",会将表单用其它的文本域与file域一起作为流提交
     *   所以此时request.getParameter()是无法获取到表单中的文本域的,这时可以借助文件上传组件来获取比如org.apache.commons.fileupload.FileItem
     * 3.RabbitMQ订阅过来的消息时,这里得到的servletRequestAttributes==null,所以加了一个判断
     */
    ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
    if(null == attributes){
        return joinPoint.proceed();
    }
    HttpServletRequest request = attributes.getRequest();
    LogUtil.getLogger().info("{}()-->{}被调用,客户端IP={},入参为[{}]", methodInfo, request.getRequestURI(), RequestUtil.getClientIP(request), JadyerUtil.buildStringFromMap(request.getParameterMap()));
    /*
     * 使用自定义注解
     */
    Method method = ((MethodSignature)joinPoint.getSignature()).getMethod();
    if(method.isAnnotationPresent(SeedLog.class)){
        SeedLog seedLog = method.getAnnotation(SeedLog.class);
        String logData = "动作:" + seedLog.action().getCode() + "(" + seedLog.action().getMsg() +")" + ",描述:" + seedLog.value();
        LogUtil.getLogger().info("{}()-->{}被调用,客户端IP={},Log注解为[{}]", methodInfo, request.getRequestURI(), RequestUtil.getClientIP(request), logData);
    }
    /*
     * 表单验证
     */
    //Object[] objs = joinPoint.getArgs();
    //for (Object obj : objs) {
    //    if (null != obj && obj.getClass().getName().startsWith("com.jadyer.seed.ucs")) {
    //        LogUtil.getLogger().info("{}()-->{}被调用, 客户端IP={}, 得到的表单参数为{}", methodInfo, request.getRequestURI(), IPUtil.getClientIP(request), ReflectionToStringBuilder.toString(obj, ToStringStyle.MULTI_LINE_STYLE));
    //        String validateResult = ValidatorUtil.validate(obj);
    //        LogUtil.getLogger().info("{}()-->{}的表单-->{}", methodInfo, request.getRequestURI(), StringUtils.isBlank(validateResult)?"验证通过":"验证未通过");
    //        if (StringUtils.isNotBlank(validateResult)) {
    //            throw new SeedException(CodeEnum.SYSTEM_BUSY.getCode(), validateResult);
    //        }
    //    }
    //}
    /*
     * 执行Controller的方法
     */
    respData = joinPoint.proceed();
    long endTime = System.currentTimeMillis();
    String returnInfo;
    if(null!=respData && respData.getClass().isAssignableFrom(ResponseEntity.class)){
        returnInfo = "ResponseEntity";
    }else{
        //出参就不再格式化输出了,因为通常接口返回的都是实体类,类属性很多,很占面积,影响查日志
        //returnInfo = JSON.toJSONStringWithDateFormat(respData, JSON.DEFFAULT_DATE_FORMAT, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullBooleanAsFalse);
        returnInfo = JSON.toJSONStringWithDateFormat(respData, JSON.DEFFAULT_DATE_FORMAT, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullBooleanAsFalse);
    }
    LogUtil.getLogger().info("{}()-->{}被调用,出参为[{}],Duration[{}]ms", methodInfo, request.getRequestURI(), returnInfo, endTime-startTime);
    LogUtil.getLogger().info("---------------------------------------------------------------------------------------------");
    //注意這里一定要原封不动的返回joinPoint.proceed()结果,若返回JSON.toJSONString(respData)则会报告下面的异常
    //java.lang.String cannot be cast to com.jadyer.seed.comm.constant.CommResult
    //这是由于JSON.toJSONString(respData)得到的是字符串,而实际Controller方法里面返回的是CommResult对象
    return respData;
}
 
Example 13
Source File: ResponseMessage.java    From hsweb-framework with Apache License 2.0 4 votes vote down vote up
@Override
public String toString() {
    return JSON.toJSONStringWithDateFormat(this, "yyyy-MM-dd HH:mm:ss");
}
 
Example 14
Source File: JsonUtil.java    From OfficeAutomatic-System with Apache License 2.0 4 votes vote down vote up
public static <T> String serializeDate(T object) {
    return JSON.toJSONStringWithDateFormat(object,"yyyy-MM-dd");
}
 
Example 15
Source File: JSONUtils.java    From NetworkDisk_Storage with GNU General Public License v2.0 2 votes vote down vote up
/**
 * 将JAVA对象转化为JSON字符串以及特定的时间格式
 * @param object JAVA 对象
 * @param dataFormat 日期格式
 */
public static final String toJSONString(Object object, String dataFormat) {
    String jsonStr = JSON.toJSONStringWithDateFormat(object, dataFormat, SerializerFeature.WriteDateUseDateFormat);
    return jsonStr;
}
 
Example 16
Source File: ZookeeperWorkerRegister.java    From idworker with Apache License 2.0 2 votes vote down vote up
/**
 * 节点信息转json字符串
 * 
 * @param nodeInfo 节点信息
 * @return json字符串
 */
private String jsonizeNodeInfo(NodeInfo nodeInfo) {
    String dateFormat = "yyyy-MM-dd HH:mm:ss";
    return JSON.toJSONStringWithDateFormat(nodeInfo, dateFormat, SerializerFeature.WriteDateUseDateFormat);
}
 
Example 17
Source File: JsonUtils.java    From android-Stupid-Adapter with Apache License 2.0 2 votes vote down vote up
/**
 * 将给定的目标日期对象转换成 JSON 日期格式的字符串。
 * 
 * @param target
 *            要转换成 JSON 的目标日期对象。
 * @return 目标对象的 JSON 日期格式的字符串。
 */
public static String toJsonDateFormat(Object date) {
	if (date == null)
		return EMPTY_JSON;
	return JSON.toJSONStringWithDateFormat(date, DEFAULT_DATE_PATTERN);
}