因公司业务需要,只显示市级别的城市按首字母顺序排列
首先解析汉字
1、引入jar包
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>
2、编写utils
@Slf4j
public class PinYinUtils {
public static String getFirst(String str) {
if(StringUtils.isEmpty(str)){
return null;
}
char[] charArray = str.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
try {
StringBuffer sb=new StringBuffer();
for (char c:charArray){
if(!Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {
continue;
}
String[] hanyuPinyinStringArray = PinyinHelper.toHanyuPinyinStringArray(c, defaultFormat);
if(hanyuPinyinStringArray==null){
continue;
}
sb.append(hanyuPinyinStringArray[0].charAt(0));
}
return sb.toString();
} catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
log.error("拼音转换失败{}",badHanyuPinyinOutputFormatCombination);
return null;
}
}
}
其次请求高德省市县接口
@RestController
@RequestMapping("/v1/cpsp")
public class CpspController {
@PostMapping("/v1/getCity")
public String getCity(){
RestTemplate restTemplate=new RestTemplate();
String url="https://restapi.amap.com/v3/config/district";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
params.add("subdistrict","2");
params.add("key","xxxxxxxxx");
HttpEntity<MultiValueMap<String, String>> httpEntity=new HttpEntity<MultiValueMap<String, String>>(params,headers);
ResponseEntity<JSONObject> responseEntity=restTemplate.exchange(url, HttpMethod.POST,httpEntity,JSONObject.class);
JSONObject jsonObject=responseEntity.getBody();
JSONArray country=jsonObject.getJSONArray("districts");
JSONArray provinces=country.getJSONObject(0).getJSONArray("districts");
Map<String,JSONObject> map=new TreeMap<>();
for(int i=0;i<provinces.size();i++){
JSONArray citys=provinces.getJSONObject(i).getJSONArray("districts");
JSONObject jsonObjectCity=null;
for(int c=0;c<citys.size();c++){
JSONObject city=citys.getJSONObject(c);
jsonObjectCity=new JSONObject();
jsonObjectCity.put("adcode",city.getString("adcode"));
jsonObjectCity.put("name",city.getString("name"));
map.put(PinYinUtils.getFirst(city.getString("name")),jsonObjectCity);
}
}
JSONObject resultJSONObject=new JSONObject();
String first="A";
List<JSONObject> list=new ArrayList<>();
for (Map.Entry<String, JSONObject> entry : map.entrySet()) {
if(first.equalsIgnoreCase(String.valueOf(entry.getKey().charAt(0)))){
list.add(entry.getValue());
}else{
resultJSONObject.put(first,list);
first=String.valueOf(entry.getKey().charAt(0));
list=new ArrayList<>();
list.add(entry.getValue());
}
}
resultJSONObject.put(first,list);
return resultJSONObject.toJSONString();
}
}
此代码有可优化空间,但是本人只是生成出来交给APP使用,故未做优化
|