java string to csv_Convert java Object to CSV

This is really more of an addition to the above post about using Jackson CSV. One issue I ran into is that it would raise any error on any properties in the object that were not in the CSV schema when I was doing it programatically and not using any annotations. Here is some example code that may be helpful. If you want to know more about why the filter and annotation introspector is necessary see here. public class CsvWriter { private final static String CSV_FILTER_NAME = "csvFilter"; public void writeObjects( OutputStream outputStream, List> objects, CsvSchema csvSchema ) throws IOException { HashSet columnNames = new HashSet(); for (CsvSchema.Column column : csvSchema) { columnNames.add( column.getName() ); } SimpleBeanPropertyFilter csvReponseFilter = new SimpleBeanPropertyFilter.FilterExceptFilter(columnNames); FilterProvider filterProvider = new SimpleFilterProvider().addFilter( CSV_FILTER_NAME, csvReponseFilter ); CsvMapper csvMapper = new CsvMapper(); csvMapper.setFilters( filterProvider ); csvMapper.setAnnotationIntrospector( new CsvAnnotationIntrospector() ); ObjectWriter objectWriter = csvMapper.writer(csvSchema); objectWriter.writeValue( outputStream, objects); } private class CsvAnnotationIntrospector extends JacksonAnnotationIntrospector { @Override public Object findFilterId(Annotated a) { return CSV_FILTER_NAME; } } }

and here is an example of how it can be used: public class CsvWriterTest extends TestCase { public void testWriteObjects() throws Exception { Vector entities = new Vector(); entities.add( new Entity("Test entity 1", "Test description 1", "Test unused field")); entities.add(new Entity("Test entity 2", "Test description 2", "Test unused field")); CsvSchema csvSchema = CsvSchema.builder() .addColumn("name") .addColumn("description") .setUseHeader( true ) .build() .withLineSeparator("\r\n"); CsvWriter csvWriter = new CsvWriter(); csvWriter.writeObjects(System.out, entities, csvSchema); } public class Entity { private String name; private String description; private String unusedField; // constructor, getter and setter methods omitted for brevity } }

Output from the test method is:

name,description

"Test entity 1","Test description 1"

"Test entity 2","Test description 2"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值