2014-07-04 58 views
1

我正在研究一個Restlet servlet,它應該能夠以不同格式(XML,JSON,CSV)提供多行數據。用JacksonRepresentation編寫多行CSV

我已經在傑克遜解決了我的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 ...

例豆和包裝:

@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; 
    } 
} 

回答

1

我認爲在當前代碼中有一個錯誤。 CSV映射器計算不正確。

爲此我輸入了一個問題(https://github.com/restlet/restlet-framework-java/issues/928),感謝報告此問題。

作爲一種解決辦法,我建議你創建JacksonRepresentation如下:

rep = new JacksonRepresentation<MyBean[]>(MediaType.TEXT_CSV, tab) { 
    @Override 
    protected ObjectWriter createObjectWriter() { 
     CsvMapper csvMapper = (CsvMapper) getObjectMapper(); 
     CsvSchema csvSchema = csvMapper.schemaFor(MyBean.class); 
     ObjectWriter result = csvMapper.writer(csvSchema); 
     return result; 
    } 
}; 

它的工作原理也與豆類的名單。

+0

工作很好,謝謝。 – jarnum

+0

有人可以編輯此代碼,使其可編譯? – Hooli