让JSON.org支持JavaBean

JSON.org包里的方法对JavaBean没有支持,而 JSON-lib虽然功能丰富,但是依赖很多其它的包,为了方便我就写了一个类继承于JSONObject,方便JavaBean的使用。

源代码:
package  net.jialing;

import  java.lang.reflect.Method;
import  java.util.StringTokenizer;

/**
 * 支持JavaBean的JSONObject
 *
 * 
@author  Michael
 * 
@since  2006-10-4
 * 
@version  0.1a
 
*/

public   class  JSONReflectObject  extends  JSONObject {
    
    
public  JSONReflectObject() {
        
super ();
    }
    
    
/**
     * 构造函数
     * 
@param  object 需要得到信息的JavaBean
     * 
@param  names 属性的字符串数组
     
*/
    
public  JSONReflectObject(Object object, String names[]) {
        
this ();
        
for  ( int  i  =   0 ; i  <  names.length; i  +=   1 ) {
            
try  {
                String name 
=  names[i];
                setProperty(object,name);
            } 
catch  (Exception e) {
                
/*  forget about it  */
            }
        }
    }
    
    
/**
     * 得到JavaBean的某个属性,支持加.得到属性的属性
     * 
     * 
@param  owner 对象
     * 
@param  property  属性名
     * 
@return  方法返回值
     * 
@throws  Exception
     
*/
    
private   void  setProperty(Object owner, String property)
            
throws  Exception {

        Class ownerClass;
        Object[] args 
=   null ;
        Class[] argsClass 
=   null ;
        

        
int  i = 0 ,loop = 0 // i表示第几层JSOBObject,loop表示循环了几次
        
        StringTokenizer st 
=   new  StringTokenizer(property, " . " );
        
        JSONObject jo[] 
=   new  JSONObject[st.countTokens() - 1 ];
        
for ( int  x = 0 ,y = jo.length;x < y;x ++ ) {
            jo[x] 
=   new  JSONObject();
        }
        
        
while  (st.hasMoreTokens()) {
            String propertyName 
=  st.nextToken();
             
          ownerClass 
=  owner.getClass();
        String methodName 
=   " get "
                        
+  propertyName.substring( 0 , 1 ).toUpperCase() 
                        
+  propertyName.substring( 1 );

        Method method 
=  ownerClass.getMethod(methodName, argsClass);
        owner 
=  method.invoke(owner, args);

        
if (st.hasMoreTokens()) {
            
if ( loop  ==   0
                
this .put(propertyName,jo[ 0 ]);
            
else  
                jo[i].put(propertyName, jo[
++ i]);
                
            loop
++ ;
        }
            
else  {
                
if (loop == 0 )
                    
this .put(propertyName, owner.toString());
                
else
                    jo[i].put(propertyName, owner.toString());
            }
            
        }

    }
    
}


测试准备:

public   class  Student {
    
private  String name;
    
private  String email;
    
private  Birthday birthday;

      getter and setter
}

public   class  Birthday {
    
private  Year year;
    
private  String month;
    
private  String day;

      
public  Birthday(String year,String month,String day){
        
this .year  =   new  Year(year);
        
this .month  =  month;
        
this .day  =  day;
    }

      getter and setter
}

public   class  Year {
    
private  String y;

      getter and setter
    
    
public  Year(String y){
        
this .y  =  y;
    }
}

测试:
public   class  Test {
    
      
public  String singleObject()  throws  JSONException {
        Student s 
=   new  Student();
        s.setName(
" Jack " );
        s.setEmail(
" [email protected] " );
        s.setBirthday(
new  Birthday( " 1990 " , " 12 " , " 30 " ));
        
        String[] params 
=  { " name " , " email " , " birthday.year.y " };
        
        JSONReflectObject jo 
=   new  JSONReflectObject(s,params);
        
return  jo.toString();
    }

      
public   static   void  main(String args[])  throws  Exception{
        test t 
=   new  test();
        System.out.println(t.singleObject());
    }
}

1.首先新建一个Student
2.设置name,email,birthday属性
3.把要打印出的属性放在字符串数组里,支持加"."得到属性的属性
4.建立JSONReflectObject,将要输出的对象和属性数组作为参数
5.打印:{"email":"[email protected]","name":"Jack","birthday":{"year":{"y":"1990"}}} 

你可能感兴趣的:(让JSON.org支持JavaBean)