需要的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()所以结果是: