Json与JavaBean相互转换
Json与JavaBean相互转换的工具有很多,比如下面附件中的struts2-json-plugin-2.1.8.1.jar。
具体实现为
String content = JSONUtil.serialize(javaBean);//将javaBean(包括Domain、List、Map等)转化为String类型的jsonJaveBean 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); Class clz = source.getClass(); String methodName = "get" + propName; Method method = null; try { method = clz.getMethod(methodName, (Class[]) null); // 寻找属性的get方法 } catch (NoSuchMethodException nsme) { String methodName2 = "is" + propName; // 也许是个is方法 try { method = clz.getMethod(methodName2, (Class[]) null); } catch (NoSuchMethodException ne) { // 没有找到属性的get或者is方法,打印错误,返回true System.err.println(“No such methods: ” + methodName + “ or “ + methodName2); return true; } } return apply(method); }} // END: AbstractMethodFilterpublic class InvisibleFilter extends AbstractMethodFilter { // 过滤条件,标注中有符合这个条件的property将被过滤掉 private String _sGUIID; public InvisibleFilter(final String guiid) { _sGUIID = guiid; } public boolean apply(final Method method) { if (_sGUIID == null || _sGUIID.equals(“”)) { return false; // 表示不做限制 } if (method.isAnnotationPresent(Invisible.class)) { Invisible anno = method.getAnnotation(Invisible.class); String[] value = anno.value(); for (int i = 0; i < value.length; i++) { if (_sGUIID.equals(value[i])) { return true; } } } return false; }}
JsonConfig config = new JsonConfig();config.setJsonPropertyFilter( new InvisibleFilter(“LIST”)); //标注了LIST的属性将被过滤掉System.out.println( JSONSerializer.toJSON( new MyBean(), config ) );// prints {"name":"json"}
JsonConfig config = new JsonConfig();config.registerJsonValueProcessor(java.util.Date.class, new JsDateJsonValueProcessor());
@Documented@Target({ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)public @interface IntegerCode { public int value();}public class IntegerCodeFilter extends AbstractMethodFilter { // 代码处理器 private IntegerCodeProcessor _processor; public IntegerCodeFilter(final IntegerCodeProcessor processor) { _processor = processor; } // 不过滤属性,但当发现IntegerCode标注时,将数据传递给Processor public boolean apply(final Method method) { if (_processor == null) { return false; // 表示没有特别的处理 } if (method.isAnnotationPresent(IntegerCode.class)) { IntegerCode anno = method.getAnnotation(IntegerCode.class); int code = anno.value(); _processor.setMainCode(code); // 将code设置为主代码 } return false; }}
public class IntegerCodeProcessor implements JsonValueProcessor { private int _iMainCode; public void setMainCode(final int mainCode) { _iMainCode = mainCode; } public IntegerCodeProcessor() { super(); } // END: IntegerCodeProcessor private void reset() { _iMainCode = -1; } public Object processArrayValue(Object value, JsonConfig jsonConfig) { return process(value, jsonConfig); } // END: processArrayValue public Object processObjectValue( String key, Object value, JsonConfig jsonConfig ) { return process( value, jsonConfig ); } // END: processObjectValue private Object process(Object value, JsonConfig jsonConfig) { if (value == null) { return null; } String ret = null; if (value instanceof Integer && _iMainCode >= 0) { int code = value.intValue(); switch (_iMainCode) { case 100: // 这里使用简单的case 处理不同的代码 if (code == 1) { // 好一点的方式是从资源文件中读取对应值 ret = "man"; } else if (code == 2) { ret = "woman"; } else { ret = value.toString(); } break; default: ret = value.toString(); break; } } else { ret = value.toString(); } reset(); // 处理后重置,以免影响其他 Integer 属性 return ret; } // END: process}
public class Student { private String name = "camry"; private int gender = 1; // getters & setters public String getName() { return name; } @IntegerCode(100) // 性别主代码为 100 public int getGender() { return gender; }}}...IntegerCodeProcessor processor = new IntegerCodeProcessor();IntegerCodeFilter filter = new IntegerCodeFilter(processor);JsonConfig config = new JsonConfig();config.setJsonPropertyFilter( filter );config.registerJsonValueProcessor(Integer.class, processor);System.out.println( JSONSerializer.toJSON( new Student(), config ) );// prints {“gender”:”man”, "name":"camry"}