How to convert JSON string into List of Java object?

前端 未结 9 2181
醉酒成梦
醉酒成梦 2020-12-01 12:12

This is my JSON Array :-

[ 
    {
        \"firstName\" : \"abc\",
        \"lastName\" : \"xyz\"
    }, 
    {
        \"firstName\" : \"pqr\",
        \"         


        
9条回答
  •  离开以前
    2020-12-01 12:35

    I made a method to do this below called jsonArrayToObjectList. Its a handy static class that will take a filename and the file contains an array in JSON form.

     List items = jsonArrayToObjectList(
                "domain/ItemsArray.json",  Item.class);
    
        public static  List jsonArrayToObjectList(String jsonFileName, Class tClass) throws IOException {
            ObjectMapper mapper = new ObjectMapper();
            final File file = ResourceUtils.getFile("classpath:" + jsonFileName);
            CollectionType listType = mapper.getTypeFactory()
                .constructCollectionType(ArrayList.class, tClass);
            List ts = mapper.readValue(file, listType);
            return ts;
        }
    

提交回复
热议问题