日期:2014-05-16 浏览次数:20390 次
String content = JSONUtil.serialize(javaBean);//将javaBean(包括Domain、List、Map等)转化为String类型的json JaveBean jb = (JaveBean)JSONUtil.deserialize(Stirng json);//将String类型的Json转化为JavaBean类型的javaBean
JSON json = JSONSerializer.toJSON( JaveBean ); JSON json = JSONSerializer.toJSON( JaveBean , jsonConfig); JaveBean jb = (JaveBean)JSONSerializer.toJava( json ); JaveBean jb = (JaveBean)JSONSerializer.toJava(json , jsonConfig);
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;
// 定义属性过滤器
PropertyFilter filter = new PropertyFilter(
    public boolean apply(Object source, String name, Object value) {
        if ( name.equals( “pojoId” ) ) {
            return true;   // 返回 true, 表示这个属性将被过滤掉
        }
        return false;
    }
);
// 注册属性过滤器
JsonConfig config = new JsonConfig();
config.setJsonPropertyFilter( filter );
System.out.println( JSONSerializer.toJSON( new MyBean(), config ) );
// prints {"name":"json"}
				
import java.lang.annotation.Target;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Invisible {
    public String[] value();
}
// 为myBean中需要过滤的属性get方法(或者is方法)加上Invisible标注
public class MyBean{
    private String name = "json";
    private int pojoId = 1;
    
    // getters & setters
    public String getName() { return name; }
    @Invisible(“LIST”)   // 在 “LIST” 情况下不要这个属性
    public int getPojoId() { return pojoId; }
}
				
import java.util.Map;
import java.lang.reflect.Method;
import net.sf.json.util.PropertyFilter;
// 先实现一个abstract类,将读取Bean属性的Method找到并传递给子类处理
public abstract class AbstractMethodFilter implements PropertyFilter {
    // 这个方法留给子类实现,以便适应不同的过滤需求
    public abstract boolean apply(final Method method);
    public boolean apply(final Object source, final String name, final Object value) {
        if (source instanceof Map) {
            return false;
        }
        String propName = name.substring(0, 1).toUpperCase() + name.substring(1);