How to convert JSON string into List of Java object?

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

This is my JSON Array :-

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


        
9条回答
  •  萌比男神i
    2020-12-01 12:41

    You can use below class to read list of objects. It contains static method to read a list with some specific object type. It is included Jdk8Module changes which provide new time class supports too. It is a clean and generic class.

    List students = JsonMapper.readList(jsonString, Student.class);
    

    Generic JsonMapper class:

    import com.fasterxml.jackson.databind.DeserializationFeature;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
    import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
    
    import java.io.IOException;
    import java.util.*;
    
    import java.util.Collection;
    
    public class JsonMapper {
    
        public static  List readList(String str, Class type) {
            return readList(str, ArrayList.class, type);
        }
    
        public static  List readList(String str, Class type, Class elementType) {
            final ObjectMapper mapper = newMapper();
            try {
                return mapper.readValue(str, mapper.getTypeFactory().constructCollectionType(type, elementType));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    
        private static ObjectMapper newMapper() {
            final ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            mapper.registerModule(new JavaTimeModule());
            mapper.registerModule(new Jdk8Module());
            return mapper;
        }
    }
    

提交回复
热议问题