Gson解析Json 一

代码:

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);
	}
	
	
}
}

运行效果图:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值