使用了Google 的Gson類進行了封裝。
大家在使用的時候別忘了導入下載google-gson-x.x.x-jar 包
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/**
* JsonUtils
* 能將封裝類或者封裝類的集合轉爲JSON
* 能將JSON解析成封裝類 或者封裝類的集合
* @author shaoduo
*/
public class JsonUtils {
/**
* 針對於bean 或者 List<bean>來說將這個 封裝對象轉爲json字符串
* @param obj
* @return String
*/
public static <T> String pubOrPubsToJson(T t)
{
Gson gson = new Gson();
String jsonStr=gson.toJson(t);
return jsonStr;
}
/**
* 判斷是否數據需要解析成JsonStr
* @param retJsonStr
* @return boolean
*/
public static boolean isNeedFromJsonToPub(String retJsonStr)
{
if(retJsonStr.length()>100)
{
return true;
//System.out.println("是否需要解析::"+);
}
return false;
}
/**
* 解析從服務器端返回的字符串轉爲pub封裝類型
* @param retJsonStr
* @param obj
*/
public static <T> T jsonToPub(String jsonString, Class<T> cls) {
T t = null;
try {
Gson gson = new Gson();
t = gson.fromJson(jsonString, cls);
} catch (Exception e) {
// TODO: handle exception
}
return t;
}
/**
* 解析從服務器端返回的字符串轉爲pubList封裝類型
* @param retJsonStr
* @param obj
*/
public static <T> List<T> jsonToPubs(String jsonString, Class<T> cls) {
List<T> list = new ArrayList<T>();
try {
Gson gson = new Gson() ;
list = gson.fromJson(jsonString, new TypeToken<List<T>>() {
}.getType());
// list=(List<T>)JSONObject.toBean(jsonString,cls);
} catch (Exception e) {
}
return list;
}
/**
* 解析從服務器端返回的字符串轉爲pubList封裝類型
* @param retJsonStr
* @param obj
*/
public static <T> List<T> JsonToPubs(String json, Class<T[]> type) {
T[] list = new Gson().fromJson(json, type);
return Arrays.asList(list);
}
}
如何使用
1. 將集合List 的 PeoplePubList 轉爲Json
String peopleListJsonStr=JsonUtils.pubOrPubsToJson(PeoplePubList);
2. 將封裝類 People 的 people 轉爲Json
String peJsonStr= JsonUtils.pubOrPubsToJson(people);
3. peopleListJsonStr的json數組解析爲 PeopleList
PeopleList = JsonUtils.JsonToPubs(getJson, People[].class) ;
或者
PeopleList = JsonUtils.jsonToPubs(getJson, People[].class) ;
4.將PeopleStr的json數組解析爲People
people=jsonToPub(PeopleStr) ;
版權聲明
author :shaoduo
原文來自:http://blog.csdn.net/shaoduo
其他出處均爲轉載,原創作品,歡迎讀者批評指正。