Spring REST Controller returns JSON with empty data [closed]

╄→尐↘猪︶ㄣ 提交于 2019-12-22 02:34:05

问题


I have a simple Spring Boot web application. I'm trying to receive some data from server. The Controller returns a collection, but the browser receives empty JSON - the number of curly brackets is equals to the number of objects from server, but its content is empty.

@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;
    }
}

The method fires and a browser shows:

Nothing more in the console. Any ideas?

EDIT: 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(){

    }
}

回答1:


I think you should use Lombok as class level instead of field level.

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

This may solve your problem.




回答2:


Do you have a converter in the project that converts JAVA objects to JSON. If not, you need on. Try using Jackson in your project.

Once Jackson jars are imported into the project, the dispatcher servlet should have below:

    <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>



回答3:


Try adding @ResponseBody to your REST method's return type declaration in the method signature. That should do it if you're using the standard Spring Boot starter project.



来源:https://stackoverflow.com/questions/39914710/spring-rest-controller-returns-json-with-empty-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!