【发布时间】:2014-07-04 07:54:16
【问题描述】:
我正在开发一个 Restlet servlet,它应该能够以不同格式(目前为 XML、JSON、CSV)提供多行数据。
我已经决定使用 Jackson 将我的 POJO 映射到不同的格式,并尝试为此目的使用 JacksonRepresentation(Restlet 扩展),但我在 CSV 位工作时遇到了一些麻烦。
如果我使用以下任一 JacksonRepresentation 构造函数:
List<MyBean> beansList = getBeans(); // Query database etc.
MyBean[] beansArr = beansList.toArray(new MyBean[beansList.size()]);
// Tried all the following
JacksonRepresentation<MyBean[]> result = new JacksonRepresentation<MyBean[]>(MediaType.TEXT_CSV, beansArr);
JacksonRepresentation<List<MyBean>> result = new JacksonRepresentation<List<MyBean>>(MediaType.TEXT_CSV, beansList);
JacksonRepresentation<ListWrapper> result = new JacksonRepresentation<ListWrapper>(MediaType.TEXT_CSV, new ListWrapper(beansList));
JacksonRepresentation<ArrayWrapper> result = new JacksonRepresentation<ArrayWrapper>(MediaType.TEXT_CSV, new ArrayWrapper(beansArr));
// Explicit schema shouldn't be necessary, since the beans are already annotated
CsvSchema csvSchema = CsvSchema.builder()
.addColumn("productcode", ColumnType.STRING)
.addColumn("quantity", ColumnType.NUMBER)
.build();
result.setCsvSchema(csvSchema);
return result;
我得到一个例外:
com.fasterxml.jackson.core.JsonGenerationException: Unrecognized column 'productcode': known columns: ]
但如果我坚持一个对象/行:
JacksonRepresentation<MyBean> result = new JacksonRepresentation<MyBean>(MediaType.TEXT_CSV, beansArr[0]);
我得到了一个包含一行数据的漂亮、有效的 CSV 文件。
对于 JSON,数组包装器方法似乎是为多个对象执行此操作的方法,但我终生无法弄清楚如何制作多行 CSV...
示例 bean 和包装器:
@JsonPropertyOrder({ "productcode", "quantity" ... })
public class MyBean {
private String productcode;
private float quantity;
public String getProductcode() {
return productcode;
}
public void setProductcode(String productcode) {
this.productcode = productcode;
}
.
.
.
}
public class ListWrapper {
private List<MyBean> beans;
public ListWrapper(List<MyBean> beans) {
setBeans(beans);
}
public void setBeans(List<MyBean> beans) {
this.beans = beans;
}
public List<MyBean> getBeans() {
return beans;
}
}
public class ArrayWrapper {
private MyBean[] beans;
public ArrayWrapper(MyBean[] beans) {
setBeans(beans);
}
public void setBeans(MyBean[] beans) {
this.beans = beans;
}
public MyBean[] beans getBeans() {
return beans;
}
}
【问题讨论】: