How to convert JSON string into List of Java object?

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

This is my JSON Array :-

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


        
9条回答
  •  无人及你
    2020-12-01 12:40

    I have resolved this one by creating the POJO class (Student.class) of the JSON and Main Class is used for read the values from the JSON in the problem.

       **Main Class**
    
        public static void main(String[] args) throws JsonParseException, 
           JsonMappingException, IOException {
    
        String jsonStr = "[ \r\n" + "    {\r\n" + "        \"firstName\" : \"abc\",\r\n"
                + "        \"lastName\" : \"xyz\"\r\n" + "    }, \r\n" + "    {\r\n"
                + "        \"firstName\" : \"pqr\",\r\n" + "        \"lastName\" : \"str\"\r\n" + "    } \r\n" + "]";
    
        ObjectMapper mapper = new ObjectMapper();
    
        List details = mapper.readValue(jsonStr, new 
          TypeReference>() {      });
    
        for (Student itr : details) {
    
            System.out.println("Value for getFirstName is: " + 
                      itr.getFirstName());
            System.out.println("Value for getLastName  is: " + 
                     itr.getLastName());
        }
    }
    
    **RESULT:**
             Value for getFirstName is: abc
             Value for getLastName  is: xyz
             Value for getFirstName is: pqr
             Value for getLastName  is: str
    
    
     **Student.class:**
    
    public class Student {
    private String lastName;
    
    private String firstName;
    
    public String getLastName() {
        return lastName;
    }
    
    public String getFirstName() {
        return firstName;
    } }
    

提交回复
热议问题