【问题标题】:Auto include CSV header with Spring MVC and jackson-dataformat-csv使用 Spring MVC 和 jackson-dataformat-csv 自动包含 CSV 标头
【发布时间】:2016-08-03 09:48:12
【问题描述】:

我正在努力使用 jackson-dataformat-csv 使其包含 CSV 标头。

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

我的 MVC 配置(缩短):

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

输出值列表的控制器:

@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 格式返回:

[
    {
      "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 格式时:

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 csv 映射器自动包含标题。标头名称应与用于 Json 的名称相同(使用实体 @Json... 注释)?

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

【问题讨论】:

    标签: csv spring-mvc jackson


    【解决方案1】:

    Jackson 使用的机制是 CsvSchema used 需要启用 header,所以类似于:

    CsvMapper mapper = new CsvMapper();
    CsvSchema schema = CsvSchema.emptySchema().withHeader();
    String csv = mapper.writer(schema).writeValueAsString(...);
    

    接下来的挑战是如何通过CsvSchema 使用;或可能的CsvWriter 配置为使用一个。我不确定 Spring MVC 是否明确支持这样做。

    【讨论】:

    • 谢谢,我最终在前端进行了 CSV 导出。这样做的主要原因是我的大多数 Web API 返回无法表示为 CSV 的深层 json 对象。
    • @singe3 是的,很难支持深度嵌套。 Jackson 可以通过 @JsonUnwrapped 来支持它,但这可能会很快变得笨拙,因此实际的结构更改可能是有意义的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 2017-03-06
    • 2017-10-24
    • 2017-10-01
    • 2017-09-20
    相关资源
    最近更新 更多