Why am I not able to deserialize an array of objects by unwrapping the root node?
import java.io.IOException;
import java.util.Arrays;
import java.util.List
This code worked for me:
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
public class RootNodeTest extends Assert {
public static class CustomerMapping {
public List customer;
public List getCustomer() {
return customer;
}
public static class Customer {
public String email;
public String getEmail() {
return email;
}
}
}
@Test
public void testUnwrapping() throws IOException {
String json = "{\"customer\":[{\"email\":\"hello@world.com\"},{\"email\":\"john.doe@example.com\"}]}";
ObjectMapper mapper = new ObjectMapper();
CustomerMapping customerMapping = mapper.readValue(json, CustomerMapping.class);
List customers = customerMapping.getCustomer();
for (CustomerMapping.Customer customer : customers) {
System.out.println(customer.getEmail());
}
}
}
First of all you need a java object for the whole json object. In my case this is CustomerMapping. Then you need a java object for your customer key. In my case this is the inner class CustomerMapping.Customer. Because customer is a json array you need a list of CustomerMapping.Customer objects. Also, you do not need to map the json array to a java array and convert it then to a list. Jackson already does it for you. Finally, you just specify the variable email of type String and print it to the console.