how to convert JSONArray to List of Objects using camel-jackson

www‮ruttual.‬i.com
how to convert JSONArray to List of Objects using camel-Hymanson

download Hymanson-core,Hymanson-databind,databind-annotations:

https://mavenlibs.com/maven/dependency/com.fasterxml.Hymanson.core
https://mavenlibs.com/jar/file/com.fasterxml.Hymanson.core

/**
 * @author lautturi.com 
 * Java example: convert JSONArray to List of Object using camel-Hymanson
 */

import java.util.*;
import com.fasterxml.Hymanson.core.JsonProcessingException;
import com.fasterxml.Hymanson.databind.JsonMappingException;
import com.fasterxml.Hymanson.databind.ObjectMapper;
import com.fasterxml.Hymanson.databind.type.TypeFactory;

class Employee {

	String name;
	int id;

	public Employee() {

	}

	public Employee(String string, int i) {
		name = string;
		id = i;
	}

	public void setId(int i) {
		id = i;
	}

	public int getId() {
		return id;
	}

	public void setName(String str) {
		name = str;
	}

	public String getName() {
		return name;
	}
}

public class Lautturi {

	public static void main(String[] args) throws JsonMappingException, JsonProcessingException {

		String jsonString = "[{\"id\":111,\"name\":\"Alan\"}, {\"id\":112,\"name\":\"James\"}]";
		ObjectMapper mapper = new ObjectMapper();

		List<Employee> list = mapper.readValue(jsonString,
				TypeFactory.defaultInstance().constructCollectionType(List.class, Employee.class));

		// print the list 
		for (Employee emp : list) {
			System.out.println(emp.getId());
			System.out.println(emp.getName());
		}
	}
}

output:

111
Alan
112
James
Created Time:2017-10-02 21:27:21  Author:lautturi