解析一个json前端字符串,写个工具类
{
"北京": {
"val": "110000",
"items": {
"东城区": "110101",
"西城区": "110102",
"崇文区": "110103",
"宣武区": "110104",
"朝阳区": "110105",
"丰台区": "110106",
"石景山区": "110107",
"海淀区": "110108",
"门头沟区": "110109",
"房山区": "110111",
"通州区": "110112",
"顺义区": "110113",
"昌平区": "110114",
"大兴区": "110115",
"怀柔区": "110116",
"平谷区": "110117",
"密云县": "110228",
"延庆县": "110229"
}
},
"天津": {
"val": "120000",
"items": {
"和平区": "120101",
"河东区": "120102",
"河西区": "120103",
"南开区": "120104",
"河北区": "120105",
"红桥区": "120106",
"塘沽区": "120107",
"汉沽区": "120108",
"大港区": "120109",
"东丽区": "120110",
"西青区": "120111",
"津南区": "120112",
"北辰区": "120113",
"武清区": "120114",
"宝坻区": "120115",
"宁河县": "120221",
"静海县": "120223",
"蓟县": "120225",
"滨海新区": "120226"
}
}
}
需要一个json jar包
<dependency>
<groupId>net.sf.json-libgroupId>
<artifactId>json-libartifactId>
<version>2.4version>
<classifier>jdk15classifier>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.39version>
dependency>
import com.alibaba.fastjson.JSON;
import net.sf.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @Author: zhangle
* @Date: 2019/8/16 10:43
* @Version 1.0
*/
public class utils {
public static List<City> convertJson(String json){
JSONObject jsonObject = JSONObject.fromObject(json);
Map<String, Object> map = (Map)jsonObject;
List<City> cityList=new ArrayList<>();
for (String cityname : map.keySet()) {
Object zijson = map.get(cityname);
City city = JSON.parseObject(zijson+"",City.class);
city.setName(cityname);
String items = city.getItems();
JSONObject areajson = JSONObject.fromObject(items);
Map<String,Object> map2 = (Map)areajson;
List<Area> areasList=new ArrayList<>();
for (String quName : map2.keySet()) {
Area area = new Area();
area.setName(quName);
Object quCode = map2.get(quName);
area.setCode(Integer.parseInt(quCode+""));
areasList.add(area);
}
city.setAreas(areasList);
cityList.add(city);
}
return cityList;
}
}
相当于一个工具类
public class City {
private String name;
private int val;
private String items;
private List<Area> areas;
}
public class Area {
private String name;
private int code;
}
祝你幸福
加粗送你一首歌:
附图:《此食此客》第四集(广州) 连载…