欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-06-07 21:23:39
...
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();