简体   繁体   English

Spring 引导:使用 JSON 发布请求

[英]Spring Boot: Post Request with JSON

I have a controller endpoint that takes EmployeeRequest as shown below:我有一个采用EmployeeRequest的 controller 端点,如下所示:

{
    "name": "Marry Boython",
    "email": "marry@gmail.com",
    "country": "UK",
    "age": "25"         
}

For creating multiple employees, I use a static list in the Application class so that they are populated to the database when running the app.为了创建多个员工,我在应用程序 class 中使用 static 列表,以便在运行应用程序时将它们填充到数据库中。 However, I want to create these employees from a json file and sending List<EmployeeRequest> to the service.但是,我想从 json 文件创建这些员工并将List<EmployeeRequest>发送到服务。

I tried the following aproach, but not sure where I point the location of my json file.我尝试了以下方法,但不确定我将 json 文件的位置指向何处。 So, is that the right approach that I am looking to read json and send list of the items in it to the service?那么,这是我希望阅读 json 并将其中的项目列表发送到服务的正确方法吗?

@PostMapping(
            value = "/createAll", consumes = "application/json", produces = "application/json")
public ResponseEntity<List<EmployeeDto>> createAll(
        @RequestBody List<EmployeeRequest> requests) {
    final List<EmployeeDto> employees = employeeService.create(requests);
    return ResponseEntity.ok(employees);
}

Ok from my understanding you would need no body as request input.好的,据我了解,您不需要正文作为请求输入。 Instead, you'd want a controller that takes as input a file name so that you can dynamically load a.json file.相反,您需要一个 controller 作为输入文件名,以便您可以动态加载 .json 文件。 Your controller method would look something like this:您的 controller 方法如下所示:

private final ObjectMapper mapper;

private final ResourceLoader resourceLoader;

public Controller(ObjectMapper mapper, ResourceLoader resourceLoader) {
    this.mapper = mapper;
    this.resourceLoader = resourceLoader;
}

@PostMapping("/load/{fileName}")
public void loadResource(@PathParam("fileName") String fileName) throws IOException {
    Resource resource =resourceLoader.getResource("classpath:"+fileName);
    log.debug("Found file " + resource.getFile().getAbsolutePath());
    List<Person> people = mapper.readValue(resource.getFile(), new TypeReference<>() {
    });
    log.info(String.valueOf(people));
}

Where the People.class would be your list of objects that are contained in the json file (EmployeeRequest) People.class将是 json 文件 (EmployeeRequest) 中包含的对象列表

Your.json files would need to be placed with this structure: Your.json 文件需要使用以下结构放置:

在此处输入图像描述

Yes.是的。 If you already have this JSON file, keep it on resources folder.如果您已经拥有此 JSON 文件,请将其保存在资源文件夹中。 Then read the JSON file.然后读取 JSON 文件。 You should write the business logic on service class that looking and put files' data into the Database.您应该在服务 class上编写业务逻辑,用于查找文件数据并将其放入数据库。

Update implementation:更新实现:

If you use maven project, update maven repository:如果您使用maven项目,请更新 maven 存储库:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
</dependency>

Now follow the code:现在按照代码:

Put this JSON "Employee.json" (Any name but update as well) into resources folder.将此 JSON “Employee.json” (除更新之外的任何名称)放入资源文件夹中。

@RestController
@RequestMapping("/createAll")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @PostMapping
    public ResponseEntity<String> createAll() {
        employeeService.create();
        return new ResponseEntity<>("Employees Inserted to DB", HttpStatus.CREATED);
    }
}

@Service
public class EmployeeService {
    // @Autowired
    // private EmployeeRepository employeeRepository;
    public void create() {
        try {
            File resource = new ClassPathResource("Employee.json").getFile();
            String employeeJson = new String(Files.readAllBytes(resource.toPath()));
            Type listType = new TypeToken<ArrayList<EmployeeDto>>() {}.getType();
            List<EmployeeDto> employees = new Gson().fromJson(employeeJson, listType);
            // Call repository method to save employee list
            // employeeRepository.saveAll(employees);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Hope your problem will be solved.希望你的问题能得到解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM