具体使用
//获取业务参数
String busiStr = req.getParameter("busiData");
if(!StringUtils.isEmpty(busiStr)){
try {
this.busiData = JsonUtils.transferToBean(busiStr);
} catch (Exception e) {}
}
将JsonObject转为Bean
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.platform.core.base.Bean;
import com.platform.core.base.IBean;
import com.platform.core.exception.CoreException;
import com.platform.util.json.JSONArray;
import com.platform.util.json.JSONException;
import com.platform.util.json.JSONObject;
/**
* @param str JSON串
* @return Bean实体
*/
public static Bean transferToBean(String str) {
Bean n = new Bean();
if (str != null && str.length() > 0) {
try {
JSONObject jsObject = new JSONObject(str);
/*Iterator is = jsObject.keys();
for (Iterator iterator = collection.iterator(); iterator
.hasNext();) {
type type = (type) iterator.next();
}*/
for (Iterator<?> i = jsObject.keys(); i.hasNext();) {
Bean[] tmpBean = new Bean[] { };
String key = (String) i.next();
Object value = jsObject.get(key);
if (value instanceof JSONArray) {
JSONArray tmpArray = (JSONArray) value;
tmpBean = new Bean[tmpArray.length()];
for (int index = 0, len = tmpArray.length(); index < len; index++) {
String subStr = tmpArray.getString(index).toString();
//处理类似"ids":["125","124"]的列表数据转换报错
if(subStr.startsWith("[") || subStr.startsWith("{"))
tmpBean[index] = transferToBean(tmpArray.getString(index).toString());
else {
tmpBean = new Bean[] {};//{"ids":["125","124"],"gridArray":[{"__PK_CODE__":"125"},{"__PK_CODE__":"124"}]}
break;
}
}
}
if (tmpBean.length > 0) {
n.set(key, tmpBean);
} else {
n.set(key, value);
}
}
} catch (JSONException e) {
throw new CoreException("JSONException: " + e.getMessage());
}
}
return n;
}
将对象转为JSON字符串
/**
* @param obj 对象
* @return JSON串 */
public static String toJson(Object obj) {
return new JSONObject(obj).toString();
}
转换json字符串数组为List<IBean>,形如[{},{}]
public static List<IBean> transferToListBean(String str) {
List<IBean> retListIBeans = new ArrayList<IBean>();
if (str != null && str.length() > 0) {
try {
JSONArray jsonArray = new JSONArray(str);
if(null != jsonArray && jsonArray.length() > 0){
for (int i = 0; i < jsonArray.length(); i++) {
String jsonString = jsonArray.getString(i);
IBean bean = transferToBean(jsonString);
retListIBeans.add(bean);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return retListIBeans;
}
将list对象转为JSON字符串
public static String toListJson(List<IBean> obj) {
return new JSONArray(obj).toString();
}