Friday, May 14, 2021

How to Convert JSON array string to List

 How to Convert JSON array string to List

1. Convert JSON array string to List

1.1 JSON array string

[{"name":"mkyong", "age":37}, {"name":"fong", "age":38}]

1.2 Create an object to map the above JSON fields.

public class Person {

    String name;

    Integer age;

    //getters and setters

}

1.3 Convert the JSON array string to a List

public class JacksonArrayExample {


    public static void main(String[] args) {


        ObjectMapper mapper = new ObjectMapper();

        String json = "[{\"name\":\"mkyong\", \"age\":37}, {\"name\":\"fong\", \"age\":38}]";


        try {


            // 1. convert JSON array to Array objects

            Person[] pp1 = mapper.readValue(json, Person[].class);


            System.out.println("JSON array to Array objects...");

            for (Person person : pp1) {

                System.out.println(person);

            }


            // 2. convert JSON array to List of objects

            List<Person> ppl2 = Arrays.asList(mapper.readValue(json, Person[].class));


            System.out.println("\nJSON array to List of objects");

            ppl2.stream().forEach(x -> System.out.println(x));


            // 3. alternative

            List<Person> pp3 = mapper.readValue(json, new TypeReference<List<Person>>() {});


            System.out.println("\nAlternative...");

            pp3.stream().forEach(x -> System.out.println(x));


        } catch (IOException e) {

            e.printStackTrace();

        }


    }

}

Output

1. JSON array to Array objects...

Person{name='mkyong', age=37}

Person{name='fong', age=38}


2. JSON array to List of objects

Person{name='mkyong', age=37}

Person{name='fong', age=38}


3. Alternative...

Person{name='mkyong', age=37}

Person{name='fong', age=38}

No comments:

Post a Comment