packagecom.apt.utils;importcom.alibaba.fastjson.JSON;importcom.alibaba.fastjson.serializer.ValueFilter;importcom.apt.model.TBTEntity;importorg.json.JSONObject;importjava.util.ArrayList;importjava.util.Iterator;importjava.util.List;/*** Created by Administrator on 2017/4/14.*/
public classJsonUtil {private final static String tag="JsonUtil";/*** 反序列化一个实体
*@paramjsonString {"Address":"北京市通州区科创六街","BaiDuLat":39.814426895001,"BaiDuLng":116.55877636322,"CellId":41776,"Lac":4388,"Lat":39.808475,"Lng":116.552281,"MNC":"0"}
*@paramclazz CellInfo.class
*@param
*@return
*/
public static Object parseObject(String jsonString,Classclazz){try{if(jsonString==null||jsonString.equals("")){return null;
}returnJSON.parseObject(jsonString, clazz);
}catch(Exception ex){
LogUtil.WriteError(ex,tag+"->toBean()");return null;
}
}/*** 反序列化一个泛型集合
*@paramjson
*@return
*/
public static List parseArray(String json,Classclazz){
List list=new ArrayList();try{
list=JSON.parseArray(json, clazz);
}catch(Exception ex){
LogUtil.WriteError(ex,tag+"->parseArray()");
}returnlist;
}/*** 反序列化一个具体集合
*@paramjson
*@return
*/
public static ListgetListTBTEntity(String json){
List list=new ArrayList();try{
list= JSON.parseArray(json, TBTEntity.class);
}catch(Exception ex){
LogUtil.WriteError(ex,tag+"->getListTBTEntity()");
}returnlist;
}public staticString toJSONString(Object clazz){
String json="";try{
json=JSON.toJSONString(clazz,filter);
}catch(Exception ex){
LogUtil.WriteError(ex,tag+"->toJSONString()");
}
json=formatJson(json);returnjson;
}//解决序列化对对象为null的字段不序列化的问题
private static ValueFilter filter = newValueFilter() {
@OverridepublicObject process(Object obj, String s, Object v) {if(v==null)return "";returnv;
}
};//解决序列后首字母变成小写的问题
private staticString formatJson(String orgJson) {
JSONObject jo= newJSONObject();try{
JSONObject jsonObject= newJSONObject(orgJson);
Iterator iterator=jsonObject.keys();while(iterator.hasNext()) {
String key=(String) iterator.next();char chars[] =key.toCharArray();if (key.length() > 1 && Character.isLowerCase(key.charAt(0))) {
chars[0] = Character.toUpperCase(chars[0]);
}
Boolean bl=jsonObject.isNull(key);if(bl) {
jo.put(new String(chars), null);
}else{
Object object=jsonObject.get(key);try{if (object instanceofNumber) {
jo.put(newString(chars),
((Number) object).intValue());
}else{
jo.put(newString(chars), jsonObject.getString(key));
}
}catch(Exception e) {
jo.put(newString(chars), jsonObject.getString(key));
}
}
}
}catch(Exception ex) {
LogUtil.WriteError(ex,tag+"->formatJson()");
}returnjo.toString();
}
}