1、功能概述?
通过Java中的反射机制功能实现该工具类,通过动态的获取bean的set和get方法解析后获取属性名称和值。
能够将java中的任意Object或者List<Object>转化成我们需要的JSON字符串。
案例:
对象:Student stu=new Student(“1001”,”雾林小妖”,”男”,”34”,”安徽合肥”,”1001”);
json字符串:
{“stu_id”:”1001”, “stu_name”:” 雾林小妖” , “stu_sex”:”男”, “stu_age”:” 34”, “stu_addr”:”安徽合肥”, “stu_pwd”:”1001”}
2、创建测试使用的Bean对象Student
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private String stu_id; //编号
private String stu_name;//姓名
private String stu_sex; //性别
private String stu_age; //年龄
private String stu_addr;//地址
private String stu_pwd; //密码
}
3、创建对象转Object2JSONUtil 工具类
obj2Json方法:通用对象转json
list2Json方法:通用集合转json
public class Object2JSONUtil {
//通用对象转json
public String obj2Json(Object obj) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
Class c1=obj.getClass();
//获取类中的方法
Method []method=c1.getDeclaredMethods();
int k=0;
StringBuffer sbf=new StringBuffer();
sbf.append("{");
for (int i = 0; i < method.length; i++) {
if(method[i].getName().startsWith("get")&&method[i].getModifiers()==Modifier.PUBLIC){
if(k!=0){
sbf.append(",");
}
String attrName=method[i].getName().substring(3).toLowerCase();
sbf.append("\""+attrName+"\"");
sbf.append(":");
//invoke通过method[i]中的定义去stu中找出method对应的底层方法
String attrValue=method[i].invoke(obj).toString();
sbf.append("\""+attrValue+"\"");
k++;
}
}
sbf.append("}");
return sbf.toString();
}
//通用集合转json
public String list2Json(List list) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
//[{},{},{}]
StringBuffer sbf=new StringBuffer();
sbf.append("[");
for(int i=0;i<list.size();i++){
if(i!=0){
sbf.append(",");
}
sbf.append(obj2Json(list.get(i)));//{}
}
sbf.append("]");
return sbf.toString();
}
}
4、程序测试
public class Test {
public static void main(String[] args) throws Exception {
Student stu=new Student(“1001”,”雾林小妖”,”男”,”34”,”安徽合肥”,”1001”);
List<Student> list=new ArrayList<Student>();
list.add(stu);
String json=new Object2JSONUtil().list2Json(list);
System.out.println(“====输出json====”+ json);
}
}