[英]How to prevent CsvMapper from including unrecognized fields in the output CSV?
When using CsvMapper
with @JsonPropertyOrder
, all fields that are not explicitly named are put at the end of the CSV record. 将
CsvMapper
与@JsonPropertyOrder
CsvMapper
使用@JsonPropertyOrder
,未明确命名的所有字段都放在CSV记录的末尾。 This means that typos result in different CSV ordering. 这意味着拼写错误导致不同的CSV排序。
Example: 例:
public class Example {
public static void main(String[] args) throws JsonProcessingException {
final CsvMapper csvMapper = new CsvMapper();
System.out.println(csvMapper.writerWithSchemaFor(MyClass.class).writeValueAsString(new MyClass("test", true, 2)));
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonPropertyOrder({"name", "code"})
public static class MyClass {
@JsonProperty("name")
private String name;
@JsonProperty("status")
private boolean status;
@JsonProperty("code")
private Integer code;
}
}
Results in: test,2,true
. 结果:
test,2,true
。 Since status
was not explicitly named in @JsonPropertyOrder
it was put in the end of the record. 由于
status
未在@JsonPropertyOrder
明确命名, @JsonPropertyOrder
它被放在记录的末尾。 I would prefer if CsvMapper
threw an exception or if it was not serialized at all. 如果
CsvMapper
抛出异常或者根本没有序列化,我更愿意。
Another example would be if I changed @JsonPropertyOrder
above to @JsonPropertyOrder({"name", "stats", "code"})
. 另一个例子是,如果我改变
@JsonPropertyOrder
上面@JsonPropertyOrder({"name", "stats", "code"})
Notice the typo in stats
. 请注意
stats
的拼写错误。 This would result in the same CSV as above. 这将产生与上述相同的CSV。
How can I configure CsvMapper
to either fail on unrecognized properties or not serialize properties not named in @JsonPropertyOrder
? 如何将
CsvMapper
配置为无法识别的属性失败或不序列化@JsonPropertyOrder
未命名的@JsonPropertyOrder
?
IMHO the only purpose of @JsonPropertyOrder
is to give you a chance of defining an order of your properties. 恕我直言
@JsonPropertyOrder
的唯一目的是让您有机会定义您的属性的顺序。 Regarding the unspecified fields you could only use the alphabetic
attribute to control their ordering. 关于未指定的字段,您只能使用
alphabetic
属性来控制它们的排序。 Consequently the annotation ignores typos and just cares about the known field names you've specified in its value attribute. 因此,注释会忽略拼写错误,只关心您在其value属性中指定的已知字段名称。
If you need a more granular control of active fields for (de-)serialization you could use @JsonIgnoreProperties
on your class or @JsonIgnore
on your fields. 如果你需要活跃的领域为(去)的序列化,你可以使用一个更精细的控制
@JsonIgnoreProperties
你的类或@JsonIgnore
你的领域。
May be this analogy is helpful: Consider an SQL statement – you SELECT
the rows in a table and ORDER
the result set afterwards. 可能这个比喻很有用:考虑一个SQL语句 - 您
SELECT
表中的行并在之后对结果集进行ORDER
。 Here the ORDER
command has also no influence on the result set's length or width. 这里的
ORDER
命令对结果集的长度或宽度也没有影响。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.