让JSON.org支持JavaBean

本文介绍了一种方法,通过扩展JSON.org的JSONObject,实现对JavaBean的支持。作者创建了一个名为JSONReflectObject的类,允许直接从JavaBean获取属性并转换为JSON格式。通过示例展示了如何使用这个新类来处理包含嵌套属性的JavaBean对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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(
" jack@a.com " );
        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":"jack@a.com","name":"Jack","birthday":{"year":{"y":"1990"}}} 
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值