以下代码仅为一个demo,是我自己封装的一个把bean转为json的方法,希望能给大家一点帮助
package com.test;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("unchecked")
public class JsonFactory {
public static void main(String[] args) throws Exception {
ImageBean image = new ImageBean(1, "aa", "aaa");
ImageBean image1 = new ImageBean(22, "2bsdb3a", "322s323aaa");
ImageBean image2 = new ImageBean(333, "aa234", "aa23sdfbsdba");
List list1 = new ArrayList();
list1.add(image);
list1.add(image1);
list1.add(image2);
List list2 = new ArrayList();
list2.add(image);
list2.add(image1);
list2.add(image2);
JsonBean jsonbean = new JsonBean("IMLC", false, list1);
JsonBean jsonbean2 = new JsonBean("IMLC", false, list2);
List list3 = new ArrayList();
list3.add(jsonbean);
list3.add(jsonbean2);
JsonFactory fc = new JsonFactory();
System.out.println(fc.getJson(list3));
}
StringBuffer json=new StringBuffer();
static{
}
public String getJson(List list) throws Exception{
json.append("[");
for (int i = 0; i < list.size(); i++) {
json.append("{");
Object obj =list.get(i);
Class invokeClass = Class.forName(obj.getClass().getName());
Method [] method = obj.getClass().getDeclaredMethods();
int count = obj.getClass().getDeclaredFields().length;
int count1 =0;
for (int j=0;j<method.length;j++) {
Method me = method[j];
String meName = me.getName();
if(meName.startsWith("get")){
count1++;
String field = meName.substring(3, meName.length()).toLowerCase();
String type = me.getReturnType().getName();
String shortType = "";
if(type.indexOf('.')>0){
shortType = type.substring(type.lastIndexOf('.')+1, type.length());
if("String".equals(shortType)){
json.append(field +":'"+invokeClass.getMethod(meName, null).invoke(obj, new Object[0])+"'");
}else if("".equals(shortType)){
}else if("".equals(shortType)){
}else if("List".equals(shortType)){
json.append(field+":");
getJson((List)invokeClass.getMethod(meName, null).invoke(obj, new Object[0]));
//json.append("}]");
}else{
}
}else if("boolean".equals(type)){
json.append(field +":'"+invokeClass.getMethod(meName, null).invoke(obj, new Object[0])+"'");
}else if("int".equals(type)){
json.append(field +":'"+invokeClass.getMethod(meName, null).invoke(obj, new Object[0])+"'");
}
if(count!=count1){
//json.append("}");
json.append(",");
}
}
}
json.append("}");
if(i!=list.size()-1){
json.append(",");
}
}
json.append("]");
return json.toString();
}
}