json字符串与对象互转

需要的jar包:

gson-2.2.4.jar

json.jar


//json字符串转对象

//json字符串转对象
	@Test
public void test5() {
Gson gson = new Gson();
String string;
try {
string = Utils.getStringByReadFile("city.json");
CityInfo citys = gson.fromJson(string, CityInfo.class);
List<City> list = citys.getCitys();
for (City city : list) {
System.out.print(city.getCode());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

封装了一个Utils类,目的是读取json文件的字符串

public class Utils {
	
	public static String getStringByReadFile(String name) {	
		InputStream fis = Utils.class.getClassLoader().getResourceAsStream(name);
		StringBuilder sb = new StringBuilder();
		byte[] bytes = new byte[128];
		int len = 0;
		try {
			while( (len = fis.read(bytes)) != -1){
				sb.append(new String(bytes,0,len));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return sb.toString();
	}
		
}

json文件:

{
	"info": [
		{
"code": "C",
"key": "028",
"nearest": "NO",
"value": "成都"
},
{
"code": "N",
"key": "0771",
"nearest": "NO",
"value": "南宁"
},
{
"code": "L",
"key": "0772",
"nearest": "NO",
"value": "柳州"
},
{
"code": "G",
"key": "0773",
"nearest": "NO",
"value": "桂林"
}
],
"resultCode": "0",
"resultInfo": "SUCCESS"
}
一个city 一个cityInof类:

public class City {
	private String code;
	private String key;
	private String nearest;
	private String value;
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getKey() {
		return key;
	}
	public void setKey(String key) {
		this.key = key;
	}
	public String getNearest() {
		return nearest;
	}
	public void setNearest(String nearest) {
		this.nearest = nearest;
	}
	public String getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}
}

public class CityInfo {
	private List<City> info;

	public List<City> getCitys() {
		return info;
	}

	public void setCitys(List<City> citys) {
		this.info = citys;
	}
}

运行结果(因为只是获取 city.getCode()所以结果是


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值