package demo;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.ttpod.common.model.Music;
/**
* @className:GsonUtil.java
* @classDescription: gson工具类
* @author:qiuchen
* @createTime:2012-9-24
*/
public class GsonUtil {
/**
* 时间格式
*/
public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
/**
* 创建GSON
* @author:qiuchen
* @createTime:2012-9-24
* @return
*/
public static Gson getGson(){
return new GsonBuilder().serializeNulls().setDateFormat(DATE_FORMAT).create();
}
/**
* 将对象转化为字符串
* @author:qiuchen
* @createTime:2012-9-24
* @param obj
* @return
*/
public String Object2Json2(Object obj){
return getGson().toJson(obj);
}
/**
* 将对象转化为字符串(泛型实现)
* @author:qiuchen
* @createTime:2012-9-24
* @param obj
* @return
*/
public static <T> String t2Json2(T t){
return getGson().toJson(t);
}
/**
* 将字符转化为对象
* @author:qiuchen
* @createTime:2012-9-24
* @param <T>
* @param jsonString
* @param clazz
* @return
*/
public static <T> T json2T(String jsonString , Class<T> clazz){
return getGson().fromJson(jsonString,clazz);
}
/**
* 将字符串数组转化为对象集合
* @author:qiuchen
* @createTime:2012-9-24
* @param <T>
* @param jsonStr
* @param type
* @return
*/
public static <T> List<T> json2Collection(String jsonStr,Type type){
return getGson().fromJson(jsonStr,type);
}
public static void main(String[] args){
//初始化一个Music对象
Music music = new Music();
music.setId(1);
music.setNeid(12322);
music.setSinger("刘德华");
music.setSong("冰雨");
music.setDownUrl("www.baidu.com");
//将music对象转化为字符串
String jsonStr = GsonUtil.t2Json2(music);
System.out.println(jsonStr);
//将json字符串转化为对象
Music m = GsonUtil.json2T(jsonStr,Music.class);
System.out.println(m.getDownUrl());
System.out.println(m.getSinger());
//对象集合
List<Music> musics = new ArrayList<Music>();
musics.add(music);
musics.add(music);
musics.add(music);
//将集合转化为字符串
String jsonStrs = GsonUtil.t2Json2(musics);
System.out.println(jsonStrs);
//将字符串转化为对象集合
List<Music> musicList = GsonUtil.json2Collection(jsonStrs,new TypeToken<List<Music>>(){}.getType());
for(Music mc : musicList){
System.out.println(mc.getSinger());
System.out.println(mc.getSong());
}
}
}