这是MetadataService 类。在 FileController 中调用此类中的方法。
这是 FileController 代码(省略细节...):
@Autowired
private MetadataService metadataService;
@PostMapping("/metadata")
public ResponseEntity<String> uploadMetadata(@RequestParam("specFile") MultipartFile specFile) {
try {
String jsonSpecFile = new String(specFile.getBytes(), StandardCharsets.UTF_8);
metadataService.parseAndSaveMetadata(jsonSpecFile);
return ResponseEntity.ok().body("Metadata uploaded successfully.");
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error uploading metadata.");
}
}
package com.example.justin_fulkerson_project.services;
import com.example.justin_fulkerson_project.entities.FileMetadataEntity;
import com.example.justin_fulkerson_project.respositories.FileMetadataRepository;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
// Service class to parse JSON spec file and save metadata to MongoDB
@Service
public class MetadataService {
private FileMetadataRepository metadataRepository;
@Autowired
public MetadataService(FileMetadataRepository metadataRepository)
{
this.metadataRepository = metadataRepository;
}
public void parseAndSaveMetadata(String jsonSpecFile) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(jsonSpecFile);
ArrayList<FileMetadataEntity> data = new ArrayList<>();
JsonNode fieldsNode = rootNode.get("fields");
if (fieldsNode.isArray()) {
for (JsonNode fieldNode : fieldsNode) {
String fieldName = fieldNode.get("name").asText();
JsonNode startNode = fieldNode.get("start");
int startPosition = startNode != null ? startNode.asInt() : 0;
JsonNode lengthNode = fieldNode.get("length");
int length = lengthNode != null ? lengthNode.asInt() : 0;
// Create an instance of FileMetadataEntity
FileMetadataEntity metadata = new FileMetadataEntity();
metadata.setFieldName(fieldName);
metadata.setStartPosition(startPosition);
metadata.setLength(length);
data.add(metadata);
System.out.println(metadata.getFieldName());
// Save the metadata to the repository
}
metadataRepository.saveAll(data);
}
}
}
在 mongoDB 集合中,两个文档被输出到集合中,而不是一个包含一个规范文件的元数据数组的文档。
这是我正在解析的 JSON 文件...
“字段”:[ { “名称”:“字段1”, “开始索引”:0, “长度”:5 }, { “名称”:“字段2”, “开始索引”:6, “长度”:10 } ] }
我尝试创建一个具有给定类型的 ArrayList 并在 for 循环的每次迭代末尾添加。
@Document
public class FileMetadataEntity
{
private List<MetaData> metaDataList;
}
创建一个新类 MetaData 并在其中添加所有字段,如名称、开始等。现在
ArrayList<FileMetadataEntity> data = new ArrayList<>();
使用 ArrayList<MetaData> data = new ArrayList<>();
并更新 FileMetadataEntity 对象中的此列表,例如 fileMetaData
,然后调用metadataRepository.save(fileMetadata) ;