How to convert JSON string into List of Java object?

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

This is my JSON Array :-

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


        
相关标签:
9条回答
  • 2020-12-01 12:40

    use below simple code, no need to use any library

    String list = "your_json_string";
    Gson gson = new Gson();                         
    Type listType = new TypeToken<ArrayList<YourClassObject>>() {}.getType();
    ArrayList<YourClassObject> users = new Gson().fromJson(list , listType);
    
    0 讨论(0)
  • 2020-12-01 12:41
    StudentList studentList = mapper.readValue(jsonString,StudentList.class);
    

    Change this to this one

    StudentList studentList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});
    
    0 讨论(0)
  • 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<Student> 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 <T> List<T> readList(String str, Class<T> type) {
            return readList(str, ArrayList.class, type);
        }
    
        public static <T> List<T> readList(String str, Class<? extends Collection> type, Class<T> 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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题