将复合java对象转换为CSV

时间:2015-08-18 23:55:42

标签: java json csv jackson org.json

我有一个对象,比如Response.java,如下所示:

class Response
{
   private User user;  // has firstName, lastName, age etc.
   private Address address; // has city, state, country etc.
   private OrderInfo orderInfo;  // has orderNumber, orderDate etc.

   // constuctors, getters/setters follow

}

我需要将这些对象的List转换为csv,所以我的最终目标是:

firstName, lastName, age, city, state, country, latitude, orderNumber, orderDate
john, doe, 25, dallas, tx, usa, somelat, 101, 08/17/2015
jane, doe, 21, atlant, ga, usa, somelat, 102, 08/15/2015

我试图使用两个库 - jackson(csv dataformat),org.json(JsonArray),但我无法获得所需的结果。

这是我的jackson csv代码:

Response response = getResponse();
final CsvMapper mapper = new CsvMapper();
final CsvSchema schema = mapper.schemaFor(Response.class);
final String csv = mapper.writer(schema).writeValueAsString(response);

杰克逊,我正在接受

com.fasterxml.jackson.core.JsonGenerationException: CSV generator does not support Object values for properties

有没有办法按照我需要的方式将复合对象转换为csv(只是没有像分组一样的json的字段)?

1 个答案:

答案 0 :(得分:6)

所以我运行了你在测试项目中使用的类似代码,看起来你需要在所有对象(User,Address和OrderInfo)上使用@JsonUnwrapped。

杰克逊CSV不支持将对象作为属性,这就是您获得该异常的原因。以下是Github上的问题:Jackson CSV Object properties issue

以下是我用来验证这一点的示例代码:

Test response = new Test();
response.setNum(1);
Stub s = new Stub();
s.setAge("12");
s.setName("Colin");
response.setS(s);
final CsvMapper mapper = new CsvMapper();
final CsvSchema schema = mapper.schemaFor(Test.class);
final String csv = mapper.writer(schema.withUseHeader(true)).writeValueAsString(response);
System.out.println(csv);

以上代码的输出如下:

num,age,name
1,12,Colin