it-source

Spring REST 컨트롤러가 빈 데이터와 함께 JSON을 반환합니다.

criticalcode 2023. 7. 25. 21:05
반응형

Spring REST 컨트롤러가 빈 데이터와 함께 JSON을 반환합니다.

나는 간단한 Spring Boot 웹 애플리케이션을 가지고 있습니다.나는 서버에서 데이터를 좀 받으려고 합니다.컨트롤러가 컬렉션을 반환하지만 브라우저는 빈 JSON을 수신합니다. 즉, 대괄호의 수는 서버의 개체 수와 동일하지만 내용은 비어 있습니다.

@RestController
public class EmployeeController {

@Autowired
private EmployeeManagerImpl employeeManagerImpl;

    @RequestMapping(path="/employees", method = RequestMethod.GET)
    public Iterable<Employee> getAllEmployees() {
        Iterable<Employee> employeesIterable = employeeManagerImpl.getAllEmployees();
        return employeesIterable;
    }
}

메서드가 실행되고 브라우저에 다음이 표시됩니다.

enter image description here

콘솔에 더 이상 없습니다.아이디어 있어요?

편집: Employee.java

@Entity
public class Employee implements Serializable{

    private static final long serialVersionUID = -1723798766434132067L;

    @Id
    @Getter @Setter 
    @GeneratedValue
    private Long id;

    @Getter @Setter
    @Column(name = "first_name")
    private String firstName;

    @Getter @Setter
    @Column(name = "last_name")
    private String lastName;

    @Getter @Setter
    private BigDecimal salary;

    public Employee(){

    }
}

저는 당신이 현장 레벨 대신 롬복을 클래스 레벨로 사용해야 한다고 생각합니다.

@Entity
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor    
public class Employee implements Serializable {}

이것은 당신의 문제를 해결할 수도 있습니다.

프로젝트에 JAVA 객체를 JSON으로 변환하는 컨버터가 있습니까?그렇지 않다면, 당신은 해야 합니다.당신의 프로젝트에서 잭슨을 사용해 보세요.

Jackson jars를 프로젝트로 가져오면 디스패처 서블릿은 다음과 같습니다.

    <beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <beans:property name="messageConverters">
            <beans:list>
                <beans:ref bean="jsonMessageConverter" />
            </beans:list>
        </beans:property>
    </beans:bean>

    <!-- Configure bean to convert JSON to POJO and vice versa -->
    <beans:bean id="jsonMessageConverter"
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    </beans:bean>

REST 메서드의 반환 형식 선언에 @ResponseBody를 메서드 서명에 추가해 보십시오.표준 Spring Boot Starter 프로젝트를 사용하는 경우에는 이 작업을 수행할 수 있습니다.

언급URL : https://stackoverflow.com/questions/39914710/spring-rest-controller-returns-json-with-empty-data

반응형