Java代码
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import com.hysoft.commons.test.User;
/************************************************************************
* JSON工具类
*
* @author cobra
* @see com.hysoft.commons.xml.JSONHelper
* @since jdk1.6
* @version version1.0
* @date 2010/09/03
*
************************************************************************/
public class JSONHelper {
/**
* 传入一个简单的List经过解析返回JSON
*
* @param list 传入参数list
*
* @return String 返回解析过后的JSON格式例如[{"abc"},{"edf"},{"xyz"}]
*/
public static String getJSONByList(List<?> list) {
StringBuffer buffer = new StringBuffer();
buffer.append("[{");
for (int i = 0; i < list.size(); i++) {
buffer.append("\"").append(list.get(i) != null ? list.get(i).toString() : "").append("\",");
}
return buffer.substring(0, buffer.length() - 1).concat("}]");
}
/**
* 传入一个Map经过解析返回JSON
*
* @param map 传入参数map
*
* @return String 返回解析过后的JSON格式例如[{"age","24","name","ty"}]
*/
@SuppressWarnings("unchecked")
public static String getJSONByMap(Map<String, Object> map) {
Iterator<?> iter = map.entrySet().iterator();
StringBuffer buffer = new StringBuffer();
buffer.append("[{");
while (iter.hasNext()) {
Map.Entry<String, Object> entry = (Map.Entry<String, Object>) iter.next();
buffer.append("\"").append(entry.getKey() != null ? entry.getKey() : "").append("\",").append("\"").append(entry.getValue() != null ? entry.getValue() : "").append("\",");
}
return buffer.substring(0, buffer.length() - 1).concat("}]");
}
/**
* 传入一个List经过解析返回JSON
*
* @param list 传入参数list
*
* @return String 返回解析过后的JSON格式例如[{"age","24","name","ty"},{"age","20","name","tt"}]
*/
public static String getJSONByBeanList(List<?> list) {
StringBuffer buffer = new StringBuffer();
try {
Class<?> clazz = list.get(0).getClass();
Field fields[] = clazz.getDeclaredFields();
buffer.append("[");
for (int i = 0; i < list.size(); i++) {
buffer.append("{");
for (int j = 0; j < fields.length; j++) {
String fieldName = fields[j].getName();
String firstLetter = fieldName.substring(0, 1).toUpperCase(); // 获得和属性对应的getXXX()方法的名字
String getMethodName = "get" + firstLetter + fieldName.substring(1); // 获得和属性对应的getXXX()方法的名字
Method getMethod = clazz.getMethod(getMethodName, new Class[] {}); // 获得和属性对应的getXXX()方法
Object value = getMethod.invoke(list.get(i), new Object[] {});
buffer.append("\"" + fieldName + "\":\"" + value + "\",");
}
buffer = new StringBuffer(buffer.substring(0, buffer.length()-1));
buffer.append("},");
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return buffer.substring(0, buffer.length() - 1).concat("]");
}
/**
* 传入一个Bean经过解析返回JSON
*
* @param object 传入参数Bean
*
* @return String 返回解析过后的JSON格式例如[{"age","24","name","ty"}]
*/
public static String getJSONByBean(Object object) {
StringBuffer buffer = new StringBuffer();
try {
Class<?> clazz = object.getClass();
Field fields[] = clazz.getDeclaredFields();
buffer.append("[{");
for (int j = 0; j < fields.length; j++) {
String fieldName = fields[j].getName();
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getMethodName = "get" + firstLetter + fieldName.substring(1);
Method getMethod = clazz.getMethod(getMethodName, new Class[] {});
Object value = getMethod.invoke(object, new Object[] {});
buffer.append("\"" + fieldName + "\":\"" + value + "\",");
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return buffer.substring(0, buffer.length() - 1).concat("}]");
}
public static String getXMLByJSON(Object object) {
return null;
}
public static void main(String[] args){
/**===========================================================================**/
List list = new ArrayList();
list.add("first");
list.add("second");
String jsonArray = JSONHelper.getJSONByList(list);
System.out.println(jsonArray);
/**===========================================================================**/
Map map = new HashMap();
map.put("name", "tianyuan");
map.put("age", "24");
String jsonMap = JSONHelper.getJSONByMap(map);
System.out.println(jsonMap);
/**===========================================================================**/
List<Object> list1 = new ArrayList<Object>();
User user0 = new User();
user0.setUsername("ty");
user0.setAge(24);
user0.setTel("137***");
user0.setAddress("南京");
list1.add(user0);
User user1 = new User();
user1.setUsername("tz");
user1.setAge(21);
user1.setTel("158***");
user1.setAddress("南京");
list1.add(user1);
String jsonList = JSONHelper.getJSONByBeanList(list1);
System.out.println(jsonList);
/**===========================================================================**/
User user2 = new User();
user2.setUsername("tianyuan");
user2.setAge(24);
user2.setTel("13770583115");
user2.setAddress("南京");
JSONArray jsonBean = JSONArray.fromObject(user0);
System.out.println(jsonBean);
}
}