How do I parse JSON objects from a JSONArray?

后端 未结 5 1201
南旧
南旧 2021-01-24 06:18

I have a very large JSON file in the following format:

[{\"fullname\": \"name1\", \"id\": \"123\"}, {\"fullname\": \"name2\", \"id\": \"245\"}, {\"fullname\": \         


        
5条回答
  •  面向向阳花
    2021-01-24 06:51

    Make your life easy and use an ObjectMapper. This way you simply define a Pojo with the same properties as you json object.

    In you case you need a Pojo that looks like this:

    public class Person{
        private String fullname;
        private int id;
    
        public Person(String fullname, int id) {
            this.fullname = fullname;
            this.id = id;
        }
    
        public String getFullname() {
            return fullname;
        }
    
        public int getId() {
            return id;
        }
    }
    

    With that you only need to do:

    ObjectMapper objectMapper = new ObjectMapper();
    List persons = objectMapper.readValue(myInputStream, TypeFactory.defaultInstance().constructCollectionType(List.class, Person.class));
    

    This is a hassle free and type safe approach.

    Dependencies needed:

    https://github.com/FasterXML/jackson-databind

    
            com.fasterxml.jackson.core
            jackson-databind
    
    

提交回复
热议问题