进来在项目中总是遇到ArrayList线性表需要转化成JSONArray的场景,或者Java对象和JSON字符串之间的转化问题,于是乎自己写了一个粗糙的工具类,经过初步的测试,暂时还未发现什么bug,现在将代码贴出来,有兴趣的朋友可以拿过去玩一玩。
首先导入jar包,fastjson-1.2.2.jar 以及 jodd-3.3.2.jar 两个jar包,在这里再次感谢温少的fastjson。谨以此向温少致敬。
上代码:
package com.sunyard.util; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.List; import jodd.bean.BeanUtil; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; /**
* JSON操作工具类
* @author jiw.yu@sunyard.com
* @time 2017-7-22
* @version 1.0
* @since 1.0
* @package com.sunyard.util
*/
public abstract class JSONUtil {
/**
* Java对象转JSON字符串
* @param @param obj
* @param @return
* @return String
* @throws
*/
public static String objectToJson(Object obj){
return JSON.toJSONString(obj);
} /**
* JSON字符串转化JAVA对象
* @param @param jsonStr
* @param @param clazz
* @param @return
* @return Object
* @throws
*/
public static Object jsonToObject(String jsonStr,Class<? extends Object> clazz){
Object obj = null;
try {
obj = clazz.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
Field[] fields = clazz.getDeclaredFields();
JSONObject json = JSONObject.parseObject(jsonStr);
for(Field f : fields){
initBean(json,f,obj);
}
return obj;
} private static void initBean(JSONObject json, Field field, Object obj) {
String fieldName = field.getName();
Class<? extends Object> clazz = obj.getClass();
Method[] methods = clazz.getDeclaredMethods();
for(Method method : methods){
Class<?> type = BeanUtil.getPropertyType(obj, fieldName);
String methodName = method.getName();
if(methodName.startsWith("set")){
methodName = methodName.substring(3, methodName.length());
String typeName = type.getName();
if("String".equals(typeName) || String.class.getName().equals(typeName)){
String fieldValue = json.getString(fieldName);
methodInvoke(method, methodName, fieldName, obj, fieldValue);
} else if("int".equals(typeName) || Integer.class.getName().equals(typeName)){
Integer fieldValue = Integer.parseInt(json.getString(fieldName));
methodInvoke(method, methodName, fieldName, obj, fieldValue);
} else if("double".equals(typeName) || Double.class.getName().equals(typeName)){
Double fieldValue = Double.parseDouble(json.getString(fieldName));
methodInvoke(method, methodName, fieldName, obj, fieldValue);
} else if("float".equals(typeName) || Float.class.getName().equals(typeName)){
Float fieldValue = Float.parseFloat(json.getString(fieldName));
methodInvoke(method, methodName, fieldName, obj, fieldValue);
} else if("long".equals(typeName) || Long.class.getName().equals(typeName)){
Long fieldValue = Long.parseLong(json.getString(fieldName));
methodInvoke(method, methodName, fieldName, obj, fieldValue);
} else if("BigDecimal".equals(typeName) || BigDecimal.class.getName().equals(typeName)){
BigDecimal fieldValue = new BigDecimal(json.getString(fieldName));
methodInvoke(method, methodName, fieldName, obj, fieldValue);
}
}
}
} private static void methodInvoke(Method method,String methodName, String fieldName,
Object obj, Object fieldValue) {
if(methodName .equalsIgnoreCase(fieldName)){
try {
method.invoke(obj, fieldValue);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
} /**
* 线性表转化为JSON数组
* @param @param list
* @param @return
* @throws Exception
*/
public static JSONArray listToJson(List<? extends Object> list) throws Exception{
JSONArray array = new JSONArray();
for(Object obj : list){
Class<? extends Object> clazz = obj.getClass();
Field[] flelds = clazz.getDeclaredFields();
Method[] methods = clazz.getMethods();
JSONObject json = new JSONObject();
for(int i = 0;i < flelds.length;i++){
String fieldName = flelds[i].getName();
for(int j = 0;j < methods.length;j++){
String methodName = methods[j].getName();
if(isGetMethod(methodName, fieldName)){
Object result = methods[j].invoke(obj,null);
json.put(fieldName.toLowerCase(), !StringUtil.isEmpty(String.valueOf(result))
? String.valueOf(result) : StringUtil.EMPTY);
}
}
}
array.add(json);
}
return array;
} /**
* 判断是否是get方法
* @param @param method
* @param @return
*/
private static boolean isGetMethod(String methodName,String fieldName){
if(methodName.startsWith("get") && !"getClass".equalsIgnoreCase(methodName)){
methodName = methodName.substring(3, methodName.length());
return StringUtil.equalsIgnoreCase(methodName, fieldName);
}
return false;
} }
编写测试方法:
public static void main(String[] args) throws Exception {
User user1 = new User();
user1.setName("张三");
user1.setAge(22);
user1.setSalary(44.33); User user2 = new User();
user2.setName("李四");
user2.setAge(33);
user2.setSalary(53.99); List<User> users = new ArrayList<User>();
users.add(user1);
users.add(user2); String user1str = objectToJson(user1);
System.out.println("测试objectToJson : " + user1str); User user = (User) jsonToObject(user1str, User.class);
System.out.println("测试jsonToObject : " + user); JSONArray array = listToJson(users);
System.out.println("测试listToJson : " + array);
}
控制台输出结果:
测试objectToJson : {"age":22,"name":"张三","salary":44.33}
测试jsonToObject : User [name=张三, age=22, salary=44.33]
测试listToJson : [{"age":"22","name":"张三","salary":"44.33"},{"age":"33","name":"李四","salary":"53.99"}]
可以很清楚的看到我们要转换的数据都转换成功了,其实表面看起来也是没有bug的,但是在某些特殊的情况下会不会有问题就不得而知了。JSON工具类,请大家参考。