代码:
import java.io.Serializable;
public class HttpEntity implements Serializable{
/**
*
*/
private static final long serialVersionUID = 100001l;
private boolean state;
private String message;
private String data;
public boolean isState() {
return state;
}
public void setState(boolean state) {
this.state = state;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public HttpEntity(boolean state, String message, String data) {
super();
this.state = state;
this.message = message;
this.data = data;
}
public HttpEntity() {
super();
}
@Override
public String toString() {
return "HttpEntity [state=" + state + ", message=" + message + ", data="
+ data + "]";
}
}
import java.util.ArrayList;
import java.util.List;
import bean.HttpEntity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class OneTest {
public static void main(String[] args) {
HttpEntity entity=new HttpEntity(true,"登录成功","这是一个简单的泛型对象解析测试");
Gson gson=new Gson();
String entityJson=gson.toJson(entity);
System.out.println("对象转Json:");
System.out.println(" "+entityJson);
HttpEntity jsonEntity=gson.fromJson(entityJson, HttpEntity.class);
System.out.println("Json转对象:");
System.out.println(" 状态:"+jsonEntity.isState());
HttpEntity entity2=new HttpEntity(false,"登录失败","这是一个简单的泛型对象解析测试");
List<HttpEntity> list=new ArrayList<HttpEntity>();
list.add(entity);
list.add(entity2);
String listParseJson=gson.toJson(list);
System.out.println("集合对象转Json:");
System.out.println(" "+listParseJson);
List<HttpEntity> jsonToEntity=gson.fromJson(listParseJson, new TypeToken<List<HttpEntity>>(){}.getType());
System.out.println("Json转集合对象:");
for (HttpEntity httpEntity : jsonToEntity) {
System.out.println(" "+httpEntity);
}
}
}
运行效果图: