当前位置: 代码迷 >> JavaScript >> json-lib反照annotation自定义字段名的转换(bean2json_str)
  详细解决方案

json-lib反照annotation自定义字段名的转换(bean2json_str)

热度:192   发布时间:2012-12-28 10:29:05.0
json-lib反射annotation自定义字段名的转换(bean2json_str)
by alex

目的,根据类的annotation,将一个对象转化为字段为annotation指定name的json字符串。

JSONBuilder builder = new JSONBuilder(response.getWriter());
builder.array();
			for (Object stat : stats) {
				
				boolean flag = stat.getClass().isAnnotationPresent(Table.class);
				String name = stat.getClass().getSimpleName();
				if (flag) {
					Table table = (Table) stat.getClass().getAnnotation(Table.class);
					name = table.name();
				}
				
				builder.object();
				builder.key(name);
				
				builder.object();
				Method[] methods = stat.getClass().getMethods();
				for (Method method : methods) {
					if (!"id".equals(method.getName()) && method.getName().startsWith("get")) {
						boolean isAnno = method.isAnnotationPresent(Column.class);
						String columnName = method.getName();
						if (isAnno) {
							Column c = method.getAnnotation(Column.class);
							columnName = c.name();
						}
						
						Object result = method.invoke(stat);
						if (result instanceof Date) {
							result = new Long(((Date)result).getTime() / 1000);
						}
						if (result instanceof Double && Double.isNaN((Double)result)) {
							result = new Double(0d);
						}
						builder.key(columnName).value(result);
					}
				}
				builder.endObject();
				
				builder.endObject();
			}
			builder.endArray();
			response.getWriter().close();
  相关解决方案