Spring BootのRestControllerでjsonを返却する方法を紹介します。RestControllerを使うと簡単にWebAPIを作成することが出来ます。WebAPIを作成するにあたって、MVCモデルに沿って説明していきます。
まずはjsonとして返却するClassを作成します。このClassがSpring Bootによってjsonに変換されて返却されます。MVCモデルで言うところのMいわゆるModelにあたります。
Modelの作成
Employee.java
package com.example.app.service;
import java.math.BigDecimal;
@Data
public class Employee {
BigDecimal salaryPerYear;
BigDecimal bankAccounts;
BigDecimal workingHoursPerDay;
public Employee(BigDecimal salaryPerYear, BigDecimal bankAccounts, BigDecimal workingHoursPerDay) {
this.salaryPerYear = salaryPerYear;
this.bankAccounts = bankAccounts;
this.workingHoursPerDay = workingHoursPerDay;
}
public Employee getSalaryPerMonth(Employee employee) {
BigDecimal salaryPerYear = employee.salaryPerYear.divide(new BigDecimal(12));
employee.bankAccounts = employee.bankAccounts.add(salaryPerYear);
return employee;
}
public Employee commute(Employee employee) {
employee.workingHoursPerDay = employee.workingHoursPerDay.add(new BigDecimal(8));
return employee;
}
}
このClassを作成するときに要注意なのが、getter/setterを付けることです。getter/setterを付けることで、Spring BootがClassをjsonに自動で変換してくれます。当記事ではLombokを使用しているのでClassの先頭に @Data を付与しています。
※getter/setterが無いと、次のようなExceptionが発生します。
org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type
Controllerの作成
次にRestControllerをマッピングするClassを作成します。このClassはクライアントからのアクセスを受け付けます。MVCで言うところのCいわゆるControllerです。
RestControllerSample.java
package com.example.app.controller;
import java.math.BigDecimal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.app.service.Employee;
@RestController
public class RestControllerSample {
@GetMapping("/employee")
private Employee sample2() {
BigDecimal salaryPerYear = new BigDecimal(1000);
BigDecimal bankAccounts = new BigDecimal(123456789);
BigDecimal workingHoursPerDay = new BigDecimal(8);
// 年収1000万、一日8時間勤務の会社員をインスタンス化
Employee employee = new Employee(salaryPerYear, bankAccounts, workingHoursPerDay);
System.out.println(employee);
return employee;
}
}
結果を確認してみます。
Viewの確認
ブラウザで http://localhost:8080/employee にアクセスします。
ブラウザにこのように出力されるはずです。
{"salaryPerYear":1000,"bankAccounts":123456789,"workingHoursPerDay":8}
ブラウザに表示されたのがMVCでいうところのVいわゆるViewで、今回はWebAPIで画面が無いためデータのみ表示されました。
json形式で返却されることが確認できました。