首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >自动包含带有Spring和jackson-dataformat-csv的CSV报头

自动包含带有Spring和jackson-dataformat-csv的CSV报头
EN

Stack Overflow用户
提问于 2016-08-03 09:48:12
回答 1查看 3.1K关注 0票数 1

我正在与杰克逊挣扎-数据格式- CSV,以使它包括CSV头。

现在,我能够输出实体的集合(列表),但是头部不存在,这使得文件无法解析,因为列没有标题。

My MVC配置(简称) :

代码语言:javascript
复制
@Configuration
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private Environment env;

    public static final String JSON_OBJECT_MAPPER_NAME = "json";
    public static final String CSV_OBJECT_MAPPER_NAME = "csv";

    private static final TimeZone OUTPUT_DATE_TIMEZONE = TimeZone.getTimeZone(ZoneOffset.UTC);
    private static final DateFormat OUTPUT_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

    @Autowired
    @Qualifier(value = JSON_OBJECT_MAPPER_NAME)
    private ObjectMapper jsonObjectMapper;

    @Autowired
    @Qualifier(value = CSV_OBJECT_MAPPER_NAME)
    private ObjectMapper csvObjectMapper;

    public MvcConfig() {
        super();
    }



    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(true);
        configurer.ignoreAcceptHeader(false);
        configurer.defaultContentType(MediaType.APPLICATION_JSON);
        configurer.useJaf(false);

        final Map<String,MediaType> mediaTypes = new HashMap<>();
        mediaTypes.put("html", MediaType.TEXT_HTML);
        mediaTypes.put("json", MediaType.APPLICATION_JSON);
        mediaTypes.put("csv", new MediaType("text","csv", Charset.forName("utf-8")));
        configurer.mediaTypes(mediaTypes);
    }




    @Bean(name = JSON_OBJECT_MAPPER_NAME)
    @Primary
    public ObjectMapper jsonObjectMapper(){
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.indentOutput(Boolean.parseBoolean(env.getProperty("jsonPrettyPrint")));
        builder.timeZone(OUTPUT_DATE_TIMEZONE);
        builder.dateFormat(OUTPUT_DATE_FORMAT);
        return builder.build();
    }

    @Bean(name = CSV_OBJECT_MAPPER_NAME)
    public ObjectMapper csvObjectMapper(){
        CsvMapper csvMapper = new CsvMapper();

        //csvMapper.enable(CsvParser.Feature.WRAP_AS_ARRAY);

        csvMapper.setTimeZone(OUTPUT_DATE_TIMEZONE);
        csvMapper.setDateFormat(OUTPUT_DATE_FORMAT);

        csvMapper.registerModule(new CsvMappingModule());
        csvMapper.registerModule(new JodaModule());

        return csvMapper;
    }



    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(createJsonHttpMessageConverter());
        converters.add(createCsvHttpMessageConverter());
    }

    private HttpMessageConverter<Object> createJsonHttpMessageConverter() {
        return createHttpMessageConverter(jsonObjectMapper, MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON_UTF8);
    }

    private HttpMessageConverter<Object> createCsvHttpMessageConverter() {
        return createHttpMessageConverter(csvObjectMapper, TEXT_CSV);
    }

    private HttpMessageConverter<Object> createHttpMessageConverter(ObjectMapper objectMapper, MediaType... supportedMediaTypes){
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(objectMapper);
        converter.setSupportedMediaTypes(Lists.newArrayList(supportedMediaTypes));
        return converter;
    }
}

:输出值列表的控制器:

代码语言:javascript
复制
@Controller
@RequestMapping("/api/history")
public class HistoricController {


    @Autowired
    public IHistoryService historyService;
    @Autowired
    public IThingService thingService;

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public List<HistoryDTO> findHistory(@PathVariable("id") Long thingId){
        Thing thing = thingService.find(thingId);
        return historyService.findByThing(thing);
    }

}

我能够以JSON格式返回:

代码语言:javascript
复制
[
    {
      "location": {
        "id": 101483,
        "name": "City A"
      },
      "dateEnteredLocation": "2016-06-06T18:44:03.000Z",
      "dateLeavingLocation": "2016-06-13T13:02:34.000Z"
    },
    {
      "location": {
        "id": 101483,
        "name": "City A"
      },
      "dateEnteredLocation": "2016-06-13T16:02:34.000Z",
      "dateLeavingLocation": "2016-06-15T11:54:57.000Z"
    },
    {
      "location": {
        "id": 101485,
        "name": "City C"
      },
      "dateEnteredLocation": "2016-06-16T04:05:06.000Z",
      "dateLeavingLocation": "2016-06-16T11:34:58.000Z"
    }
]

,但是当我尝试使用CSV格式时,我获得:

代码语言:javascript
复制
2016-06-06T18:44:03.000Z,2016-06-13T13:02:34.000Z,101483,City A
2016-06-13T16:02:34.000Z,2016-06-15T11:54:57.000ZZ,101483,City A
2016-06-16T04:05:06.000Z,2016-06-16T11:34:58.000Z,101485,City C

所以CSV的格式很好。但是没有包括标题。我需要标题,以使文件可理解的人或机器。

如何使jackson映射器自动包含标头。标题名称应该与用于Json的名称相同(使用Entity @Json.) ?

我想让它尽可能通用。我不想为CSV编写特定的MVC控制器。

EN

回答 1

Stack Overflow用户

发布于 2016-08-23 22:11:24

Jackson使用的机制是CsvSchema uses需要启用header,所以如下所示:

代码语言:javascript
复制
CsvMapper mapper = new CsvMapper();
CsvSchema schema = CsvSchema.emptySchema().withHeader();
String csv = mapper.writer(schema).writeValueAsString(...);

因此,面临的挑战是如何通过CsvSchema来使用;或者配置为使用一个的可能的CsvWriter。我不确定Spring是否对此有明确的支持。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38740089

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档