jackson 序列化 csv 属性顺序

use*_*799 9 java csv serialization jackson fasterxml

我们有一个包含 350 多列的表。生成了 pojo 类并且 getter 的顺序被搞乱了。尝试使用 jackson 的 csvmapper,但它根据 getter 顺序生成 csv。@JsonPropertyOrder 也不能使用,因为有很多列。我们在 xml 中维护列排序,并且可以在运行时生成字段顺序数组。我们可以在运行时覆盖以提供用于属性排序的字段名数组吗?我们可以使用注释内省器进行自定义吗?

小智 13

您正在寻找的称为 MappingFeature。您需要禁用属性的字母数字排序,默认情况下启用:

CsvMapper mapper = new CsvMapper();
mapper.disable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY);
Run Code Online (Sandbox Code Playgroud)

有关更多信息,您可以在此处找到:添加功能CsvSchema以允许定义排序 #42


Pet*_*lin 6

以防万一您在 2020 年到达这里,这直接来自文档

那么如何获取 CSV Schema 实例来使用呢?有3种方法:

  • 基于 Java 类创建模式
  • 手动构建架构。
  • 使用 CSV 文档的第一行获取架构的名称(无类型)以下是上述情况的代码:
// Schema from POJO (usually has @JsonPropertyOrder annotation)
CsvSchema schema = mapper.schemaFor(Pojo.class);

// Manually-built schema: one with type, others default to "STRING"
CsvSchema schema = CsvSchema.builder()
        .addColumn("firstName")
        .addColumn("lastName")
        .addColumn("age", CsvSchema.ColumnType.NUMBER)
        .build();

// Read schema from the first line; start with bootstrap instance
// to enable reading of schema from the first line
// NOTE: reads schema and uses it for binding
CsvSchema bootstrapSchema = CsvSchema.emptySchema().withHeader();
ObjectMapper mapper = new CsvMapper();
mapper.readerFor(Pojo.class).with(bootstrapSchema).readValue(json);
Run Code Online (Sandbox Code Playgroud)


Jer*_*kes -1

我相信您在这里唯一的选择是uniVocity-parsers,因为它允许您选择要写入的列以及按什么顺序:

CsvWriterSettings settings = new CsvWriterSettings();
// Sets the file headers (used for selection only, these values won't be written automatically)
settings.setHeaders("Year", "Make", "Model", "Description", "Price");

// Selects which fields from the input should be written. In this case, fields "make" and "model" will be empty
// The field selection is not case sensitive
settings.selectFields("description", "price", "year");

//configures the writer process java beans with annotations (assume TestBean has a few annotated fiedls)
settings.setRowWriterProcessor(new BeanWriterProcessor<TestBean>(TestBean.class));

// Creates a writer with the above settings;
CsvWriter writer = new CsvWriter(new File("/path/to/output.csv"), settings);

// Writes the headers specified in the settings
writer.writeHeaders();

//creates a bean instance for writing
TestBean bean = new TestBean();
bean.setPrice(new BigDecimal("500.33"));
bean.setDescription("Blah,blah");
bean.setYear(1997);

//writes it
writer.processRecord(bean);

writer.close();
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你。

披露:我是这个库的作者,它是开源且免费的(Apache 2.0 许可证)