关于对象转json字符串存在Date类型转换格式问题解决方案


public static String getJsonString4JavaPOJO(Object javaObj,final String dateFomart) {
		JSONObject json = null;
		try {
			/*修复在Integer类型如果为null转换还是null,不会被转为0*/
			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.registerDefaultValueProcessor(Integer.class, new DefaultValueProcessor() {
	            public Object getDefaultValue(Class type) {
	                return null;
	            }
	        });
			jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor(){
				@Override
				public Object processArrayValue(Object obj, JsonConfig jsonconfig) {
					return process(obj);
				}
				@Override
				public Object processObjectValue(String s, Object obj, JsonConfig jsonconfig) {
					return process(obj);
				}
				private Object process(Object obj) {
					if (obj == null) {// 如果时间为null,则返回空字串 "yyyy-MM-dd hh:mm:ss"
						return "";
					}
					if (obj instanceof Date) {
						obj = new java.util.Date(((Date) obj).getTime());
					}
					if (obj instanceof java.util.Date) {
						SimpleDateFormat sdf = new SimpleDateFormat(dateFomart,
								Locale.CHINA);// 
						return sdf.format(obj);
					} else {
						return new Object();
					}
				}
			});
			/*****end******/
                        //对象
			json = JSONObject.fromObject(javaObj , jsonConfig);
                       //集合
                       // json = JSONArray.fromObject(javaObj , jsonConfig);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json.toString();

	}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM