标签:features object public null import
import java.lang.reflect.Field;
import java.util.Date;
import java.util.Map;
import org.hibernate.Hibernate;
import abc.dao.Student;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.PropertyPreFilter;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.alibaba.fastjson.serializer.SerializerFeature;
public class JsonUtils {
public static String toJSONString(Object object, boolean filterNull, SerializerFeature[] features) {
SerializeWriter out = new SerializeWriter();
JSONSerializer serializer = new JSONSerializer(out);
for (int i = 0; i < features.length; i++) {
SerializerFeature feature = features[i];
serializer.config(feature, true);
}
serializer.setDateFormat("yyyy-MM-dd HH:mm:ss");
serializer.config(SerializerFeature.WriteDateUseDateFormat, true);
//根据PropertyName判断是否序列化
serializer.getPropertyPreFilters().add(new PropertyPreFilter() {
public boolean apply(JSONSerializer serializer, Object object, String name) {
try {
if (((object instanceof Map)) || ((object instanceof Iterable))) {
return true;
}
Field f = object.getClass().getDeclaredField(name);
if (!f.isAccessible()) {
f.setAccessible(true);
}
Object val = f.get(object);
return Hibernate.isInitialized(val);
} catch (NoSuchFieldException localNoSuchFieldException) {
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
});
serializer.write(object);
String s = out.toString();
out.close();
return s;
}
public static String toJSONString(Object object) {
return toJSONString(object, false, new SerializerFeature[0]);
}
public static void main(String[] args) {
Student aa = new Student();
aa.setName("lxg");
aa.setBirstday(new Date());
System.out.println(toJSONString(aa));
}
}
//定义一个枚举类,枚举类中也可以定义方法,属性;这样枚举对象就有对应的方法和属性了。
//使用时就比较方便了,例如:String name = SearchType.SaveHistory.name;
//枚举类其实可以用静态常量类代替,但是其不能像枚举类那样,又可以为常量再定义属性和方法。
public enum SearchType {
SaveHistory("saveHisPly cost", "保存历史", "1"),
Quote("==============报价处理", "报价", "2"),
EdrApply("==============提交批改申请单", "提交申请", "3"),
EdrApplyUMSTask("批改任务:EdrApplyUMSTask", "创建资料审核任务", "4");
public String keyword;
public String name;
public String code;
private SearchType(String keyword, String name, String code) {
this.keyword = keyword;
this.name = name;
this.code = code;
}
public static SearchType matchByCode(String c) {
if ("1".equals(c))
return SaveHistory;
if ("2".equals(c))
return Quote;
if ("3".equals(c)) {
return EdrApply;
}
if ("4".equals(c)) {
return EdrApplyUMSTask;
}
return null;
}
}
http://www.csdn.net/article/2014-09-25/2821866
下面是springmvc的相关资料
http://jinnianshilongnian.iteye.com/blog/1594806
http://www.admin10000.com/document/6436.html
对象转换成json串时,将null属性去除;以及枚举类的使用
标签:features object public null import
原文地址:http://6817977.blog.51cto.com/6807977/1765905