Gson list处理,代码优化
- 源码片段
ParameterizedTypeImpl.class
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/**
* <pre>
* author : Haitao
* e-mail : haitao_ni@foxmail.com
* time : 2017/08/07
* desc : Gson 反序列化Type类
* version: 1.0
* </pre>
*/
public class ParameterizedTypeImpl implements ParameterizedType {
private final Class raw;
private final Type[] args;
public ParameterizedTypeImpl(Class raw, Type[] args) {
this.raw = raw;
this.args = args != null ? args : new Type[0];
}
@Override
public Type[] getActualTypeArguments() {
return args;
}
@Override
public Type getRawType() {
return raw;
}
@Override
public Type getOwnerType() {
return null;
}
}
JSON2Class.class
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import java.lang.reflect.Type;
import java.util.List;
/**
* <pre>
* author : Haitao
* e-mail : haitao_ni@foxmail.com
* time : 2017/8/7
* desc : Json字符串转class
* version: 1.0
* </pre>
*/
public class JSON2Class {
private static Gson mGson = new Gson();
/**
* json 字符串转Object
* @param json
* @param typeOfT
* @param <T>
* @return
* @throws JsonSyntaxException
*/
public static <T> T fromJsonObject(String json, Class<T> typeOfT) throws JsonSyntaxException {
if (json == null) {
return null;
} else {
return mGson.fromJson(json, typeOfT);
}
}
/**
* json字符串转List<T>
* @param json
* @param clazz
* @param <T>
* @return
* @throws JsonSyntaxException
*/
public static <T> List<T> fromJsonArray(String json, Class<T> clazz) throws JsonSyntaxException {
if (json == null) {
return null;
} else {
Type listType = new ParameterizedTypeImpl(List.class, new Class[]{clazz});
return mGson.fromJson(json, listType);
}
}
public static Gson getGson() {
return mGson;
}
}
- Model类
NoticeDBean.class
public class NoticeDBean {
/**
* "id": "1",
* "title": "测试公告",
* "createtime": "2017-07-18 21:50:33"
*/
private String id;
private String title;
private String createtime;
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCreatetime() {
return this.createtime;
}
public void setCreatetime(String createtime) {
this.createtime = createtime;
}
}
- 使用示例
String jsonObjectStr="{"id":"3","title":"测试公告","createtime":"2017-08-04 16:44:08"}";
String jsonArrayStr="[{"id":"3","title":"测试公告","createtime":"2017-08-04 16:44:08"},{"id":"3","title":"测试公告","createtime":"2017-08-04 16:44:08"}]";
NoticeDBean notice=JSON2Class.fromJsonObject(jsonObjectStr,NoticeDBean.class);
List<NoticeDBean> notice = JSON2Class.fromJsonArray(jsonArrayStr,NoticeDBean.class);