1. 程式人生 > >Android 之gson字串轉java bean

Android 之gson字串轉java bean

import com.google.gson.Gson;
import com.google.gson.JsonNull;
import com.google.gson.JsonSyntaxException;
import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONObject;
import java.lang.reflect.Type;

public class JsonUtils {
    // 定義jackson物件
    private static final ObjectMapper MAPPER = new
ObjectMapper(); // 採取單例模式 private static Gson gson = new Gson(); private JsonUtils() { } /** * @param src :將要被轉化的物件 * @return :轉化後的JSON串 * @MethodName : toJson * @Description : 將物件轉為JSON串,此方法能夠滿足大部分需求 */ public static String toJson(Object src) { if
(null == src) { return gson.toJson(JsonNull.INSTANCE); } try { return gson.toJson(src); } catch (JsonSyntaxException e) { e.printStackTrace(); } return null; } /** * @param json * @param classOfT * @return
* @MethodName : fromJson * @Description : 用來將JSON串轉為物件,但此方法不可用來轉帶泛型的集合 */
public static <T> Object fromJson(String json, Class<T> classOfT) { try { return gson.fromJson(json, (Type) classOfT); } catch (JsonSyntaxException e) { System.out.println(e.toString() + "------------------------------"); e.printStackTrace(); } return null; } /** * 將json結果集轉化為物件 * * @param jsonData json資料 * @param beanType * @param <T> 物件中的object型別 * @return */ public static <T> T jsonToPojo(String jsonData, Class<T> beanType) { try { T t = MAPPER.readValue(jsonData, beanType); return t; } catch (Exception e) { System.out.println(e.toString() + "------------------------------"); e.printStackTrace(); } return null; } /** * @param json * @param typeOfT * @return * @MethodName : fromJson * @Description : 用來將JSON串轉為物件,此方法可用來轉帶泛型的集合,如:Type為 new * TypeToken<GiveLikeList<T>>(){}.getType() * ,其它類也可以用此方法呼叫,就是將List<T>替換為你想要轉成的類 */ public static Object fromJson(String json, Type typeOfT) { try { return gson.fromJson(json, typeOfT); } catch (JsonSyntaxException e) { e.printStackTrace(); } return null; } /** * 獲取json中的某個值 * * @param json * @param key * @return */ public static String getValue(String json, String key) { try { JSONObject object = new JSONObject(json); return object.getString(key); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 獲取json中的list值 * * @param json * @return */ public static String getListValue(String json) { try { JSONObject object = new JSONObject(json); return object.getString("list"); } catch (Exception e) { e.printStackTrace(); } return null; } public static Double getDoubleValue(String json, String key) { try { JSONObject object = new JSONObject(json); return object.getDouble(key); } catch (Exception e) { e.printStackTrace(); } return null; } public static int getIntValue(String json, String key) { try { JSONObject object = new JSONObject(json); return object.getInt(key); } catch (Exception e) { e.printStackTrace(); } return 0; } }