地区码 和 地级市

104 阅读1分钟
  1. Spring boot 2.7.6
  2. java 17
  3. lombok

area.json

[
  {
    "code": "11",
    "name": "北京市",
    "children": [
      {
        "code": "1101",
        "name": "市辖区",
        "children": [
          {
            "code": "110101",
            "name": "东城区"
          }
          ......
        ]
      }
      ......
    ]
  }
  ......
]

Entity

@Data
@AllArgsConstructor
@NoArgsConstructor
public class AreaEntity {
    private String code;
    private String name;
    private List<AreaEntity> children;
}

AreaResource

@Component
@RequiredArgsConstructor
public class AreaResource {

    private final ObjectMapper objectMapper;

    // 扁平列表
    private List<AreaEntity> list;

    @Value("classpath:static/area.json")
    private Resource areaRes;

    /**
     * 扁平化对象
     * @param tree 结构树
     * @return 扁平化对象
     */
    public static List<AreaEntity> getList(List<AreaEntity> tree) {
        return tree.stream()
                .flatMap(areaEntity -> {
                    if (areaEntity.getCode().length() < 6) {
                        String rootName = areaEntity.getName();

                        return getList(areaEntity.getChildren()).stream()
                                .peek(child -> child.setName(rootName + " " + child.getName()));
                    }
                    return Stream.of(areaEntity);
                })
                .toList();
    }

    /**
     * 地区码<int> 转化为 地区对象<Structure>
     * @param code 地区码
     * @return 地区对象<Structure>
     */
    public Optional<AreaEntity> decode(String code) {
        return list.stream()
                .filter(areaEntity -> Objects.equals(areaEntity.getCode(), code))
                .findFirst();
    }

    /**
     * 地区名<String> 转化为 地区对象<Structure>
     *
     * @param area 地区名<Structure.name>
     * @return 地区对象<Structure>
     */
    public Optional<AreaEntity> parse(String area) {
        return list.stream()
                .filter(areaEntity -> Objects.equals(areaEntity.getName(), area))
                .findFirst();
    }

    @PostConstruct
    public void init() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(areaRes.getInputStream()));
        List<AreaEntity> tree = objectMapper.readValue(br, new TypeReference<>() {});
        list = AreaResource.getList(tree);
    }
}

test

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class AreaResourceTest {

    @Autowired
    AreaResource area;

    @Test
    public void parser() {
        area.parse("上海市 市辖区 黄浦区").ifPresent(System.out::println);
        // AreaEntity(code=310101, name=上海市 市辖区 黄浦区, children=null)
    }

    @Test
    public void decode() {
        area.decode("310101").ifPresent(System.out::println);
        // AreaEntity(code=310101, name=上海市 市辖区 黄浦区, children=null)
    }
}