Jackson – Convert JSON array string to List

Hello everyone, Today we will learn how to convert JSON array String to List

1.JSON array string

[
{
"name": "knowledgefactory1",
"salaray": 1000
},
{
"name": "knowledgefactory2",
"salaray": 1200
}
]

2. Create an object to map the above JSON fields.

package com.knf;

public class Employee {

String name;
Double salaray;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Double getSalaray() {
return salaray;
}

public void setSalaray(Double salaray) {
this.salaray = salaray;
}

@Override
public String toString() {
return "Employee [name=" + name + ", salaray=" + salaray + "]";
}

}

3.Convert the JSON array string to a List

package com.knf;

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\":\"knowledgefactory1\", \"salaray\":1000}, {\"name\":\"knowledgefactory2\", \"salaray\":1200}]";
try {
// 1. convert JSON array to Array objects
Employee[] pp1 = mapper.readValue(json, Employee[].class);
System.out.println("JSON array to Array objects...");
for (Employee person : pp1) {
System.out.println(person);
}
// 2. convert JSON array to List of objects
List<Employee> ppl2 = Arrays.asList(mapper.readValue(json, Employee[].class));
System.out.println("\nJSON array to List of objects");
ppl2.stream().forEach(x -> System.out.println(x));
// 3. alternative
List<Employee> pp3 = mapper.readValue(json, new TypeReference<List<Employee>>() {
});
System.out.println("\nAlternative...");
pp3.stream().forEach(x -> System.out.println(x));

} catch (IOException e) {
e.printStackTrace();
}

}
}

Output:

JSON array to Array objects...
Employee [name=knowledgefactory1, salaray=1000.0]
Employee [name=knowledgefactory2, salaray=1200.0]

JSON array to List of objects
Employee [name=knowledgefactory1, salaray=1000.0]
Employee [name=knowledgefactory2, salaray=1200.0]

Alternative...
Employee [name=knowledgefactory1, salaray=1000.0]
Employee [name=knowledgefactory2, salaray=1200.0]

pom.xml

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

Comments