博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
读取省市区
阅读量:5333 次
发布时间:2019-06-15

本文共 6960 字,大约阅读时间需要 23 分钟。

package com.hikvision.building.cloud.neptune.community.biz.service;import java.io.IOException;import java.util.ArrayList;import java.util.List;import java.util.concurrent.TimeUnit;import org.apache.commons.lang3.StringUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.StringRedisTemplate;import org.springframework.stereotype.Service;import com.fasterxml.jackson.core.type.TypeReference;import com.hikvision.building.cloud.neptune.community.biz.Utils.FileUtils;import com.hikvision.building.cloud.neptune.community.biz.Utils.JSONUtil;import com.hikvision.building.cloud.neptune.community.biz.constant.Constant;import com.hikvision.building.cloud.neptune.community.biz.vo.Province;/** *  * @author xujian18 * @version 2017年11月13日下午17:47 * @since 2017年11月13日 */@Servicepublic class ProvinceCityService {    @Autowired    private StringRedisTemplate provinceTemplate;        final List
provinces=parseProvince("province/provinces.json"); final List
cities=parseProvince("province/cities.json"); final List
areas=parseProvince("province/areas.json"); public List
findProvinceCityByParentId(String parentId) { List
all=new ArrayList<>(); List
news=new ArrayList<>(); //缓存没有 String j = provinceTemplate.opsForValue().get(Constant.PROVINCE_CITY_AREA ); if(StringUtils.isBlank(j)){ all.addAll(provinces); all.addAll(cities); all.addAll(areas); if(StringUtils.isBlank(parentId)){ return provinces; }else{ for(Province p:all){ if(StringUtils.isNotBlank(p.getParent_code())){ if(p.getParent_code().equals(parentId)){ news.add(p); } } } String json = JSONUtil.toJson(all); provinceTemplate.opsForValue().set(Constant.PROVINCE_CITY_AREA , json ,1, TimeUnit.DAYS); return news; } }else{ //缓存有 TypeReference
> typeReference = new TypeReference
>(){}; List
collection = JSONUtil.toCollection(j, typeReference); for(Province p:collection){ if(StringUtils.isNotBlank(p.getParent_code())){ if(p.getParent_code().equals(parentId)){ news.add(p); } }else{ all.add(p); } } if(StringUtils.isBlank(parentId)){ return all; }else{ return news; } } } private List
parseProvince(String area) { String JsonContext = null; try { if(System.getProperty("os.name")!=null && System.getProperty("os.name").contains("Windows")){ area = this.getClass().getClassLoader().getResource(area).getPath(); }else{ area = "/neptune-community/" + area; } JsonContext = new FileUtils().ReadFile(area); } catch (IOException e) { throw new RuntimeException(e); } TypeReference
> typeReference = new TypeReference
>(){}; List
collection = JSONUtil.toCollection(JsonContext,typeReference ); return collection; } public static void main(String[] args) { ProvinceCityService sss = new ProvinceCityService(); System.out.println(sss.areas.size()); System.out.println(sss.cities.size()); System.out.println(sss.provinces.size()); } }
package com.hikvision.building.cloud.neptune.community.biz.Utils;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;public class FileUtils {    public String ReadFile(String Path) throws IOException{        BufferedReader reader = null;        String laststr = "";        try {            File f = new File(Path);            InputStream fileInputStream = new FileInputStream(f);             InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");            reader = new BufferedReader(inputStreamReader);            String tempString = null;            while ((tempString = reader.readLine()) != null) {                laststr += tempString;            }            reader.close();        } finally {            if (reader != null) {                reader.close();            }        }        return laststr;    }}

 

package com.hikvision.building.cloud.neptune.community.biz.Utils;import java.io.IOException;import java.util.Map;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import com.fasterxml.jackson.annotation.JsonInclude;import com.fasterxml.jackson.core.type.TypeReference;import com.fasterxml.jackson.databind.DeserializationFeature;import com.fasterxml.jackson.databind.ObjectMapper;public class JSONUtil {    private static Logger logger = LoggerFactory.getLogger(JSONUtil.class);    private static ObjectMapper objectMapper = new ObjectMapper();    static {        // 排除值为空属性        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);        // 转换成对象时,没有属性的处理,忽略掉        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);        // 进行缩进输出        // configure(SerializationFeature.INDENT_OUTPUT, true);        // 进行日期格式化        // if (dateFormatPattern != null) {        // DateFormat dateFormat = new SimpleDateFormat(dateFormatPattern);        // objectMapper.setDateFormat(dateFormat);        // }    }    /**     * 将 POJO 对象转为 JSON 字符串     */    public static 
String toJson(T pojo) { try { return objectMapper.writeValueAsString(pojo); } catch (Exception e) { logger.error("toJson Failed.", e); throw new RuntimeException("转换json格式异常"); } } /** * 将 JSON 字符串转为 POJO 对象 */ public static
T fromJson(String json, Class
type) { try { return objectMapper.readValue(json, type); } catch (Exception e) { logger.error("fromJson Failed.", e); throw new RuntimeException("json格式错误" + json); } } /** * JSON串转换为Java泛型对象,可以是各种类型,此方法最为强大。用法看测试用例。 * * @param
* @param jsonString * JSON字符串 * @param tr * TypeReference,例如: new TypeReference< List
>(){} * @return List对象列表 */ public static
T toCollection(String jsonStr, TypeReference
typeReference) { try { return objectMapper.readValue(jsonStr, typeReference); } catch (Exception e) { logger.error("toCollection Failed.", e); throw new RuntimeException("json格式错误" + jsonStr); } } public static Map
json2map(String jsonStr) { if (jsonStr == null) { throw new RuntimeException("jsonStr is null"); } try { return objectMapper.readValue(jsonStr, Map.class); } catch (Exception e) { logger.error("json2map Failed.", e); throw new RuntimeException("json格式错误" + jsonStr); } } public static
T map2pojo(Map
map, Class
clazz) { return objectMapper.convertValue(map, clazz); } public static String object2Json(Object obj) { if (obj == null) { logger.error("obj is null."); throw new RuntimeException("入参错误"); } try { return objectMapper.writeValueAsString(obj); } catch (IOException e) { logger.error("object2Json Failed.", e); throw new RuntimeException("转换json格式异常"); } }}

 

转载于:https://www.cnblogs.com/xjatj/p/9140788.html

你可能感兴趣的文章
Java四种引用包括强引用,软引用,弱引用,虚引用。
查看>>
spring注入Properties
查看>>
微信小程序开发之从相册获取图片 使用相机拍照 本地图片上传
查看>>
【BZOJ-2295】我爱你啊 暴力
查看>>
【BZOJ-1055】玩具取名 区间DP
查看>>
Oracle安装配置—64位Win7安装配置64位Oracle
查看>>
Bit Twiddling Hacks
查看>>
个人总结
查看>>
[USACO08MAR]土地征用Land Acquisition
查看>>
Windwos中的线程同步
查看>>
LeetCode : Reverse Vowels of a String
查看>>
时间戳与日期的相互转换
查看>>
获取手机当前经纬度的方法
查看>>
oracle 导出与导入
查看>>
规避字符串在传递过程中造成的编码问题
查看>>
HTTP协议
查看>>
jmeter(五)创建web测试计划
查看>>
使用git pull文件时和本地文件冲突怎么办?
查看>>
python基本数据类型
查看>>
1305: [CQOI2009]dance跳舞 - BZOJ
查看>>