我有一个complex.json
文件,我希望它转换成CSV文件使用Java Spring启动。
complex.json
文件:
{
"requestId": "1P02XV425KCASEZGQLB8LPQMF4ZXCURRR01",
"recyleBinRecords": [
{
"Record": {
"ProductName": "Name1",
"Id": "1P02XV425KCASEZGQLB8LPQMF4ZXCUBCTA01"
"ProductArea": "Area1"
},
"dependecyMaterial": [
{
"Name": "D1",
"id": "1P02XV425KCASEZGQLB8LPQMF4ZXCUBCTA01",
"parentid": "1P02XV425KCASEZGQLB8LPQMF4ZXCUBCTA01",
"value": "Value1"
},
{
"Name": "d2",
"id": "1P02XV425KCASEZGQLB8LPQMF4ZXCUBCTA01",
"parentid": "1P02XV425KCASEZGQLB8LPQMF4ZXCUBCTA01",
"value": "value2"
}]},{
"Record": {
"ProductName": "Name2",
"Id": "1P02XV425KCASEZGQLB8LPQMF4ZXCUBCTA01",
"ProductArea": "Product2"
},
"dependecyMaterial": [
{
"Name": "D3",
"id": "1P02XV425KCASEZGQLB8LPQMF4ZXCUBCTA01",
"parentid": "P1",
"value": "value1"
},
{
"Name": "D4",
"id": "1P02XV425KCASEZGQLB8LPQMF4ZXCUBCTA01",
"parentid": "P2",
"value": "value2"
}
]
}
]
}
下面是我尝试的代码,但它给没有列异常.
JsonNode jsonTree = new ObjectMapper().readTree(new File("src/main/resources/complex.json"));
Builder csvSchemaBuilder = CsvSchema.builder();
JsonNode firstObject = jsonTree.elements().next();
firstObject.fieldNames().forEachRemaining(fieldName -> {csvSchemaBuilder.addColumn(fieldName);} );
CsvSchema csvSchema = csvSchemaBuilder.build().withHeader();
CsvMapper csvMapper = new CsvMapper();
csvMapper.writerFor(JsonNode.class)
.with(csvSchema)
.writeValue(new File("src/main/resources/orderLines.csv"), jsonTree);Copy
需要一个解决方案来转换我的JSON到CSV在java。
造成这种情况的原因有几个。您得到异常的主要原因是您的csv模式没有要映射的列。运行调试器,查看JsonNode firstObject = jsonTree.elements().next();
返回的行以及运行firstObject.fieldNames().forEachRemaining(fieldName -> {csvSchemaBuilder.addColumn(fieldName);} );
时向模式添加的字段。话虽如此,由于CSV生成器不支持嵌套对象,解析可能仍然无法通过。有几种方法可以处理这个问题。您可以编写自定义方法来处理该结构并输出扁平数据,或者使用库来处理转换。我过去使用的一种方法是使用JOLT库(json到json转换)对json进行预处理,创建一个临时文档并对其进行解析。从spring-boot控制器
返回一个JSON响应作为CSV文件