JSONObject Javaオブジェクトの転送方法

1398 ワード

	private Object json2Object(JSONObject json,Class pojo) throws Exception{
		        //  pojo 
		Field [] fields = pojo.getDeclaredFields();
		        //  Class pojo 
		Object obj = pojo.newInstance();
		for(Field field: fields){
		            //  ( , )
			field.setAccessible(true);
		            //  
		    String name = field.getName();
		            //  JSONObject , , 。
		    try{
		    	json.get(name);
		    }catch(Exception ex){
		        continue;
		    }
		    if(json.get(name) != null && !"".equals(json.getString(name))){
		                //  , 。
		    	if(field.getType().equals(Long.class) || field.getType().equals(long.class)){
		    		field.set(obj, Long.parseLong(json.getString(name)));
		        }else if(field.getType().equals(String.class)){
		        	field.set(obj, json.getString(name));
		        } else if(field.getType().equals(Double.class) || field.getType().equals(double.class)){
		        	field.set(obj, Double.parseDouble(json.getString(name)));
		        } else if(field.getType().equals(Integer.class) || field.getType().equals(int.class)){
		        	field.set(obj, Integer.parseInt(json.getString(name)));
		        } else if(field.getType().equals(java.util.Date.class)){
		            field.set(obj, Date.Parse(json.getString(name)));
		        }else{
		            continue;
		        }
		    }
		}
		return obj;
	}