- Spring boot 2.7.6
- java 17
- 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;
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();
}
public Optional<AreaEntity> decode(String code) {
return list.stream()
.filter(areaEntity -> Objects.equals(areaEntity.getCode(), code))
.findFirst();
}
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);
}
@Test
public void decode() {
area.decode("310101").ifPresent(System.out::println);
}
}