使用opencsv 4.0,我将数据写入文件并将其发送到外部系统
X,Y,Z
如果外部系统无法处理,我们会收到如下错误,
语法:error_code,原始提交的文本
1,X,Y,Z
现在我使用ColumnPositionMappingStrategy来解析文件中的这些数据。是否可以指定最后一个位置,以便我将所有最初提交的文本作为一个字符串,即X,Y,Z.Right现在,当我使用ColumnPositionMappingStrategy时,我只得到X并且休息Y,Z被忽略。
import java.io.StringReader;
import com.opencsv.bean.ColumnPositionMappingStrategy;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.enums.CSVReaderNullFieldIndicator;
public class OpenCsvApp {
public static void main(String[] args) {
String[] memberFieldsToBindTo = { "errorCode", "rejectionText" };
ColumnPositionMappingStrategy<Response> strategy = new ColumnPositionMappingStrategy<>();
strategy.setType(Response.class);
strategy.setColumnMapping(memberFieldsToBindTo);
String line = "1,X,Y,Z";
StringReader reader = new StringReader(line);
CsvToBeanBuilder<Response> csvBuilder = new CsvToBeanBuilder<>(reader);
csvBuilder.withMappingStrategy(strategy);
csvBuilder.withIgnoreLeadingWhiteSpace(true);
csvBuilder.withFieldAsNull(CSVReaderNullFieldIndicator.EMPTY_SEPARATORS);
CsvToBean<Response> csvToBean = csvBuilder.build();
Response response = csvToBean.parse().get(0);
reader.close();
System.out.format("errorCode: %s, rejectionText: %s", response.getErrorCode(), response.getRejectionText());
}
}
public class Request {
private String field1;
private String field2;
private String field3;
public String getField1() {
return field1;
}
public void setField1(String field1) {
this.field1 = field1;
}
public String getField2() {
return field2;
}
public void setField2(String field2) {
this.field2 = field2;
}
public String getField3() {
return field3;
}
public void setField3(String field3) {
this.field3 = field3;
}
}`
public class Response {
private String errorCode;
private String rejectionText;
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getRejectionText() {
return rejectionText;
}
public void setRejectionText(String rejectionText) {
this.rejectionText = rejectionText;
}
}
输出:errorCode:1,rejectionText:X
我想让rejectionText成为X,Y,Z
答案 0 :(得分:0)
问题是您的输出格式不正确。请记住,在CSV文件中,逗号是一个分号,因此,是1将进入错误代码,X将进入拒绝文本,Y和Z将丢失,因为您的响应只有两个字段,而您传入了四个字段。如果要让X,Y,Z成为一个字段,则需要在数据中使用引号,以便opencsv知道这都是一个字段。
"1","X,Y,Z"
希望有帮助:)