xuwenhao2002

 

自己动手写的生成json的工具类。能够动态的添加属性,属性过滤,属性名称映射

public class CreateJsonData
{

 private static final String stringType = "java.lang.String";
 private static final String intType = "int";
 private static final String doubleType = "double";

 private static final String floatType = "float";
 private static final String longType = "long";
 private static final String booleanType = "boolean";

 private static final String objectIntType = "java.lang.Integer";
 private static final String objectBooleanType = "java.lang.Boolean";
 private static final String objectDoubleType = "java.lang.Double";
 private static final String objectFloatType = "java.lang.Float";
 private static final String objectLongType = "java.lang.Long";

 private static final String[] basicTypes = {intType, objectIntType,
   floatType, longType, booleanType, doubleType, objectBooleanType,
   objectDoubleType, objectFloatType, objectLongType};
 private static final String listType="java.util.List";

 /*
  * @desc 取得对象的set方法名称
  */
 private static Map<String, String> getFieldNames(Object obj)
 {
  Class<? extends Object> cla = obj.getClass();
  Field field[] = cla.getDeclaredFields();
  Map<String, String> map = new HashMap<String, String>(0);
  for (int i = 0; i < field.length; i++)
  {
   String name = field[i].getName();
   String str = name.substring(0, 1).toUpperCase() + name.substring(1);
   map.put("get" + str, field[i].getType().getName());
  }
  return map;
 }
 /*
  * @desc调用Bean的get方法生成json数据格式
  *
  * @Par obj Bean对象
  *
  * @par map get方法名和返回参数类型
  *
  * @par config 原有字段与自定义字段的映射关系
  *
  * @par filter 过滤字段集合
  */

 private static boolean isFilter(List<String> list,String fieldName)
 {
  boolean isTag = false;
  for (int i = 0; i < list.size(); i++)
  {
   if (fieldName.equals(list.get(i)))
   {
    isTag = true;
   }
   if (isTag)
   {
    break;
   }
  }
  return isTag;
 }
 /*
  * @desc返回json数据
  */
 public static String objectToJson(Object obj,ConfigData config) throws Exception
 {
  String jsonStr=invok(obj,config);
  if(!(config.getDynicMap().isEmpty()))
  {
   jsonStr=jsonStr.substring(0,jsonStr.length()-1);
  }
  Map<String,Object> dynicMap=config.getDynicMap();
  for(Entry<String,Object> entry:dynicMap.entrySet())
  {
   jsonStr=jsonStr+execute(entry.getValue(),entry.getKey());
  }
  if(!(config.getDynicMap().isEmpty()))
  {
   jsonStr=jsonStr+"}";
  }
  return jsonStr;
 }
 private static String execute(Object obj,String property) throws Exception
 {
  Map<String,String> map=getFieldNames(obj);
  Class<? extends Object> cla = obj.getClass();
  String jsonStr = ","+property+":{";
  for(Entry<String,String> entry:map.entrySet())
  {
   Method method = cla.getDeclaredMethod(entry.getKey());
   String fieldName = methodToField(entry.getKey());
   Object object = method.invoke(obj);
   Object ob = object == null ? "" : object;
   if (isBasicType(entry.getValue()))
   {
    jsonStr = jsonStr + "\"" + fieldName + "\":" + ob.toString()
      + ",";
   }
   else if (isStringType(entry.getValue()))
   {
    jsonStr = jsonStr + "\"" + fieldName + "\":\"" + ob.toString()
      + "\",";
   }
   
   else
   {
    Object obb = Class.forName(entry.getValue()).newInstance();
    jsonStr = jsonStr + "\"" + fieldName + "\":"
      + execute(obb,fieldName) + ",";
   }
   
  }
  jsonStr = jsonStr.substring(0, jsonStr.length() - 1);
  jsonStr = jsonStr + "}";
  return jsonStr;
 }
 
 private static String invok(Object obj,ConfigData config) throws Exception
 {
  Map<String,String> map=getFieldNames(obj);
  Class<? extends Object> cla = obj.getClass();
  String jsonStr = "{";
  for (Entry<String, String> b : map.entrySet())
  {
   Method method = cla.getDeclaredMethod(b.getKey());
   String fieldName = methodToField(b.getKey());
   /*
    * 属性过滤
    */
   boolean isTag = isFilter(config.getFilterList(),fieldName);
   if (isTag)
   {
    continue;
   }
   /*
    * 属性映射
    */
   fieldName = config.getMap().get(fieldName) == null ? fieldName : config.getMap()
     .get(fieldName);
   Object object = method.invoke(obj);
   Object ob = object == null ? "" : object;
   if (isBasicType(b.getValue()))
   {
    jsonStr = jsonStr + "\"" + fieldName + "\":" + ob.toString()
      + ",";
   }
   else if (isStringType(b.getValue()))
   {
    jsonStr = jsonStr + "\"" + fieldName + "\":\"" + ob.toString()
      + "\",";
   }
   
   else
   {
    Object obb = Class.forName(b.getValue()).newInstance();
    jsonStr = jsonStr + "\"" + fieldName + "\":"
      + invok(obb, config) + ",";
   }
  }
  jsonStr = jsonStr.substring(0, jsonStr.length() - 1);
  jsonStr = jsonStr + "}";
  return jsonStr;
 }
 /*
  * @desc 验证参数类型是否为:int,float,double,long,boolean return true 是 return false
  * 不是
  */
 private static boolean isBasicType(String type)
 {
  boolean isType = false;
  for (int i = 0; i < basicTypes.length; i++)
  {
   if (basicTypes[i].equals(type))
   {
    isType = true;
   }
  }
  return isType;
 }
 /*
  * 验证参数类型是否为:String类型 return true 是 return false 不是
  */
 private static boolean isStringType(String type)
 {
  boolean isType = false;
  if (stringType.equals(type))
  {
   isType = true;
  }
  return isType;
 }
 /*
  * @desc 根据set方法名获取字段名称
  */
 private static String methodToField(String methodName)
 {
  String name = methodName.substring(3);
  String field = name.substring(0, 1).toLowerCase() + name.substring(1);
  return field;
 }
 
 public static String arrayToJson(Object obj,ConfigData config) throws JsonException
 {
  Class<? extends Object> cla=obj.getClass();
  Class<? extends Object>[] clas=cla.getInterfaces();
  boolean isTag=false;
  String jsonStr="[";
  for(int i=0;i<clas.length;i++)
  {
   if(clas[i].getName().equals(listType))
   {
    isTag=true;
   }
  }
  if(!isTag)
  {
   throw new JsonException("该类没有实现List接口 ");
  }
  try
  {
   Method method=cla.getDeclaredMethod("size");
   Object object=method.invoke(obj);
   int size=Integer.parseInt(object.toString());
   for(int i=0;i<size;i++)
   {
    method=cla.getDeclaredMethod("get",int.class);
    Object obb=method.invoke(obj,i);
    jsonStr=jsonStr+objectToJson(obb,config)+",";
   }
   jsonStr = jsonStr.substring(0, jsonStr.length() - 1);
   jsonStr=jsonStr+"]";
  } catch (SecurityException e)
  {
   e.printStackTrace();
  } catch (NoSuchMethodException e)
  {
   e.printStackTrace();
  }
   catch (InvocationTargetException e)
   {
    e.printStackTrace();
   }
   catch(IllegalAccessException e)
   {
    e.printStackTrace();
   }
   catch(Exception e)
   {
    e.printStackTrace();
   }
  return jsonStr;
 }
}

posted on 2010-04-08 20:07 xuwenhao 阅读(1494) 评论(0)  编辑  收藏 所属分类: java


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

留言簿

文章分类

文章档案

搜索

最新评论