GSON
import com.google.gson.Gson;
public class JsonUtils {
public static String createJsonObject(Object obj) {
Gson gson = new Gson();
String str = gson.toJson(obj);
return str;
}
}
二、解析JSON
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
;
public class GsonTools {
public GsonTools() {
// TODO Auto-generated constructor stub
}
/**
* @param
* @param jsonString
* @param cls
* @return
*/
public static T getPerson(String jsonString, Class cls) {
T t = null;
try {
Gson gson = new Gson();
t = gson.fromJson(jsonString, cls);
} catch (Exception e) {
// TODO: handle exception
}
return t;
}
/**
* 使用Gson进行解析 List
*
* @param
* @param jsonString
* @param cls
* @return
*/
public static List getPersons(String jsonString, Class cls) {
List list = new ArrayList();
try {
Gson gson = new Gson();
list = gson.fromJson(jsonString, new TypeToken>() {
}.getType());
} catch (Exception e) {
}
return list;
}
/**
* @param jsonString
* @return
*/
public static List getList(String jsonString) {
List list = new ArrayList();
try {
Gson gson = new Gson();
list = gson.fromJson(jsonString, new TypeToken>() {
}.getType());
} catch (Exception e) {
// TODO: handle exception
}
return list;
}
public static List> listKeyMaps(String jsonString) {
List> list = new ArrayList>();
try {
Gson gson = new Gson();
list = gson.fromJson(jsonString,
new TypeToken>>() {
}.getType());
} catch (Exception e) {
// TODO: handle exception
}
return list;
}
}
FastJSON
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
public class JsonTool {
public static T getPerson(String jsonstring, Class cls) {
T t = null;
try {
t = JSON.parseObject(jsonstring, cls);
} catch (Exception e) {
// TODO: handle exception
}
return t;
}
public static List getPersonList(String jsonstring, Class cls) {
List list = new ArrayList();
try {
list = JSON.parseArray(jsonstring, cls);
} catch (Exception e) {
// TODO: handle exception
}
return list;
}
public static List> getPersonListMap1(
String jsonstring) {
List> list = new ArrayList>();
try {
list = JSON.parseObject(jsonstring,
new TypeReference>>() {
}.getType());
} catch (Exception e) {
// TODO: handle exception
}
return list;
}
}