Saturday, June 26, 2010

Command Pattern and Generics in Java - JSON Story (3)

So what I want to do is to put a list of the same objects into List<Map<String,String>>. I created some converters for convert single object into <Map<String,String>>;. When I start to write the list converter, I realize that I only need a generic one and use the command pattern.
Here is the list converter:


public class ConverterToList<T> {



public List<Map<String,String>> convertToList(Collection<T> collection, ConverterToMap<T> converter){

List<Map<String,String>> list=new ArrayList<Map<String,String>>();
for (T t:collection){
list.add(converter.convertToMap(t));
}
return list;
}

}

And the interface for command


public interface ConverterToMap<T> {

public Map<String,String> convertToMap(T t);

}

A sample implementation

public class ConverterToMapJob implements ConverterToMap<Job> {

@Override
public Map<String, String> convertToMap(Job job) {
Map<String, String> map = new HashMap<String, String>();

JsonHelper helper = new JsonHelper(map);

helper.addCheckNull(job.getId(), "id");

helper.addCheckNull(job.getSubmitTimestamp(), "submitTimestamp");
helper.addCheckNull(job.getScheduleTimestamp(), "scheduleTimestamp");
helper.addCheckNull(job.getEndTimestamp(), "endTimestamp");
helper.addCheckNull(job.getUpdateTimestamp(), "updateTimestamp");
helper.addCheckNull(job.getHost(), "host");
helper.addCheckNull(job.getName(), "name");
helper.addCheckNull(job.getPort(), "port");
//now I am free to put any bean. Even not a bean.
helper.addCheckNull(job.getJobStatus(), "status");
return map;
}

}


I am fairly happy with this. This structure only handles a flat object or an array of it, and not general enough for more complex multi-level objects. But that fits my needs now and in the foreesable future of this project. I probably will hang with it and leave the json problem in my back. It is generally not a good idea to reinvent the wheel, but when the wheel is too complicated for your car, maybe it is better to roll your own.

No comments :