Jackson – Convert JSON array string to List

Few Jackson examples to convert a JSON array string to a List


	// JSON array string
	// [{"name":"mkyong", "age":37}, {"name":"fong", "age":38}]
	
	ObjectMapper mapper = new ObjectMapper();
	String json = "[{\"name\":\"mkyong\", \"age\":37}, {\"name\":\"fong\", \"age\":38}]";
	
	// 1. convert JSON array to Array objects
	Person[] pp1 = mapper.readValue(json, Person[].class);
	
	// 2. convert JSON array to List of objects
	List<Person> ppl2 = Arrays.asList(mapper.readValue(json, Person[].class));
pom.xml

	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-databind</artifactId>
		<version>2.9.8</version>
	</dependency>

P.S Tested with Jackson 2.9.8

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.


package com.mkyong;

public class Person {

    String name;
    Integer age;

    //getters and setters
}

1.3 Convert the JSON array string to a List

JacksonArrayExample.java

package com.mkyong;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Arrays;
import java.util.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}

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar