Вот код FileController (детали опущены...):
Код: Выделить всё
@Autowired
private MetadataService metadataService;
@PostMapping("/metadata")
public ResponseEntity 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 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);
}
}
}
Вот файл JSON, который я анализирую...
"fields": [
{
"name": "field1",
"startIndex": 0,
"length": 5
},
{
"name": "field2",
"startIndex": 6,
"length ": 10
}
]
Я попробовал создать ArrayList с заданными типами и добавить его в конце каждой итерации цикла for. .
Подробнее здесь: https://stackoverflow.com/questions/781 ... odb-databa