Jackson to List object

the code

the first method

   @Test
    public void importProvince() throws IOException {
    
    

        String fileName = "C:\\Users\\Windows3\\Documents\\province.json";


        StringBuilder sb = new StringBuilder();
        // 转换成List<String>, 要注意java.lang.OutOfMemoryError: Java heap space
        List<String> lines = Files.readAllLines(Paths.get(fileName),
                StandardCharsets.UTF_8);
        lines.forEach(val -> sb.append(val));
        System.out.println(sb.toString());
		//objectMapperFace 是装饰器 里面是ObjectMapper 
        ObjectMapper objectMapper = objectMapperFace.getObjectMapper();
        List<Pos> posList = objectMapper.readValue(sb.toString(), getCollectionType(List.class,Pos.class));
        System.out.println(posList);


        int dictValue = 1;
 

        for (Pos pos : posList) {
    
    
            List<City> citys = pos.getCity();
            for (City city : citys) {
    
    
                for (String area : city.getArea()) {
    
    
                    System.out.println(area);
                }
            }
        }
    }

   /*
     * 获取泛型的Collection Type
     * @param collectionClass 泛型的Collection
     * @param elementClasses 元素类
     * @return JavaType Java类型
     * @since 1.0
     */
    public JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
    
    
        return objectMapperFace.getObjectMapper().getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }

The second method

  TypeReference<List<Pos>> typeReference = new TypeReference<List<Pos>>() {
    
    
        };
        ObjectMapper objectMapper = objectMapperFace.getObjectMapper();
        List<Pos> posList = objectMapper.readValue(sb.toString(), typeReference);

Effect

insert image description here

problems encountered

  • Jackson from Array value (token JsonToken.START_ARRAY)

The JSON data and the field structure of the entity are inconsistent. I reported this error because the city field is an array, and the entity is written as an object.

  • non-static inner classes like this can only by instantiated using default, no-argument constructor

Appears in the internal class, the class should add statickeywords.

Guess you like

Origin blog.csdn.net/baidu_19473529/article/details/129459962