将复合Java对象转换为CSV [英] convert composite java object to CSV

查看:876
本文介绍了将复合Java对象转换为CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,例如Response.java,看起来像以下内容:

I have an object, say Response.java that looks like the following:

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

}

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

I need to convert a List of these objects into csv, so my end goal is something like:

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数据格式),org.json(JsonArray),但是我无法获得所需的结果.

I tried to use two libraries - jackson (csv dataformat), org.json (JsonArray), but i couldn't get the desired result.

这是我的杰克逊csv代码:

This is my jackson csv code:

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

有了杰克逊,我就得到了

With Jackson, i am getting

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

是否有一种方法可以按照我需要的方式将复合对象转换为csv(只是没有分组的json之类的字段)?

Is there a way to convert the composite object into csv in the way i need (just the fields without the json like grouping)?

推荐答案

所以我运行了一个在测试项目中使用的类似代码,看起来您将需要在所有对象(用户,地址,和OrderInfo).

So I ran similar code that you are using in a test project and it looks like you will need to use @JsonUnwrapped on all your objects (User, Address, and OrderInfo).

Jackson CSV不支持将对象作为属性,这就是为什么会出现该异常的原因.这是Github上的问题:杰克逊CSV对象属性问题

Jackson CSV doesn't support objects as properties which is why you got that exception. Here is the issue on Github: Jackson CSV Object properties issue

这是我用来验证的示例代码:

Here is sample code I used to verify this:

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

这篇关于将复合Java对象转换为CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆