package com.apt.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.apt.model.TBTEntity;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Created by Administrator on 2017/4/14.
*/
public class JsonUtil {
private final static String tag="JsonUtil";
/**
* 反序列化一个实体
* @param jsonString {"Address":"北京市通州区科创六街","BaiDuLat":39.814426895001,"BaiDuLng":116.55877636322,"CellId":41776,"Lac":4388,"Lat":39.808475,"Lng":116.552281,"MNC":"0"}
* @param clazz CellInfo.class
* @param <T>
* @return
*/
public static <T> Object parseObject(String jsonString,Class<T> clazz){
try{
if(jsonString==null||jsonString.equals("")){
return null;
}
return JSON.parseObject(jsonString, clazz);
}
catch(Exception ex){
LogUtil.WriteError(ex,tag+"->toBean()");
return null;
}
}
/**
* 反序列化一个泛型集合
* @param json
* @return
*/
public static <T>List<T> parseArray(String json,Class<T> clazz){
List<T> list=new ArrayList<T>();
try{
list = JSON.parseArray(json, clazz);
}
catch(Exception ex){
LogUtil.WriteError(ex,tag+"->parseArray()");
}
return list;
}
/**
* 反序列化一个具体集合
* @param json
* @return
*/
public static List<TBTEntity> getListTBTEntity(String json){
List<TBTEntity> list=new ArrayList<TBTEntity>();
try{
list = JSON.parseArray(json, TBTEntity.class);
}
catch(Exception ex){
LogUtil.WriteError(ex,tag+"->getListTBTEntity()");
}
return list;
}
public static String toJSONString(Object clazz){
String json="";
try{
json = JSON.toJSONString(clazz,filter);
}
catch(Exception ex){
LogUtil.WriteError(ex,tag+"->toJSONString()");
}
json=formatJson(json);
return json;
}
//解决序列化对对象为null的字段不序列化的问题
private static ValueFilter filter = new ValueFilter() {
@Override
public Object process(Object obj, String s, Object v) {
if(v==null)
return "";
return v;
}
};
//解决序列后首字母变成小写的问题
private static String formatJson(String orgJson) {
JSONObject jo = new JSONObject();
try {
JSONObject jsonObject = new JSONObject(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 instanceof Number) {
jo.put(new String(chars),
((Number) object).intValue());
} else {
jo.put(new String(chars), jsonObject.getString(key));
}
} catch (Exception e) {
jo.put(new String(chars), jsonObject.getString(key));
}
}
}
} catch (Exception ex) {
LogUtil.WriteError(ex,tag+"->formatJson()");
}
return jo.toString();
}
}