package com.xt.hb.data.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

/**
 * Created by myhnuhai on 2014/9/5.
 */
public class GsonUtil {
    private final  static Gson bean2Gson = new GsonBuilder().setDateFormat(DateUtil.DATE_SECOND_FMT).create();
    private final static Gson gson2Bean = new GsonBuilder().setDateFormat(DateUtil.DATE_SECOND_FMT).create();

    /**Object转String
     *
     * @param obj 对象
     * @return java.lang.String
     */
    public static String bean2gson(Object obj){
        if(obj != null){
        	return bean2Gson.toJson(obj);
        }
        return "";
    }

    /**
     * String转Object
     * @param gson
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T gson2Bean(String gson,Class<T> clazz){
    	if(gson != null){
            System.out.println(gson);
            try{
                return gson2Bean.fromJson(gson,clazz);
            }catch (Exception e){
            	e.printStackTrace();
                return  null;
            }
        }
        return null;
    }

    /**
     * String 转复杂对象
     * @param gson
     * @param typeToken
     * @param <T>
     * @return
     */
    public static  <T> T gson2Bean(String gson,TypeToken<T> typeToken){
        if(gson != null){
            try{
                return gson2Bean.fromJson(gson, typeToken.getType());
            }catch (Exception e){
            	e.printStackTrace();
                return  null;
            }
    	}
        return null;
    }
 
}
