读取省市区

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日
 */
@Service
public class ProvinceCityService {
    @Autowired
    private StringRedisTemplate provinceTemplate;
    
    final List<Province> provinces=parseProvince("province/provinces.json");
    final List<Province> cities=parseProvince("province/cities.json");
    final List<Province> areas=parseProvince("province/areas.json");

    public List<Province> findProvinceCityByParentId(String parentId) {
        List<Province> all=new ArrayList<>();
        List<Province> 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<List<Province>> typeReference = new TypeReference<List<Province>>(){};
            List<Province> 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<Province> 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<List<Province>> typeReference = new TypeReference<List<Province>>(){};
         List<Province> 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 <T> 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> T fromJson(String json, Class<T> type) {
        try {
            return objectMapper.readValue(json, type);
        } catch (Exception e) {
            logger.error("fromJson Failed.", e);
            throw new RuntimeException("json格式错误" + json);
        }
    }

    /**
     * JSON串转换为Java泛型对象,可以是各种类型,此方法最为强大。用法看测试用例。
     * 
     * @param <T>
     * @param jsonString
     *            JSON字符串
     * @param tr
     *            TypeReference,例如: new TypeReference< List<FamousUser> >(){}
     * @return List对象列表
     */
    public static <T> T toCollection(String jsonStr, TypeReference<T> 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> T map2pojo(Map<?, ?> map, Class<T> 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

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值