java Spring REST Controller 返回带有空数据的 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39914710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring REST Controller returns JSON with empty data
提问by Radziasss
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.
我有一个简单的 Spring Boot Web 应用程序。我正在尝试从服务器接收一些数据。Controller 返回一个集合,但浏览器收到空的 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;
}
}
The method fires and a browser shows:
方法触发,浏览器显示:
Nothing more in the console. Any ideas?
控制台中没有更多内容。有任何想法吗?
EDIT: Employee.java
编辑: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(){
}
}
回答by Pedro Tavares
I think you should use Lombok as class level instead of field level.
我认为您应该使用 Lombok 作为类级别而不是字段级别。
@Entity
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Employee implements Serializable {}
This may solve your problem.
这可能会解决您的问题。
回答by HARDI
Do you have a converter in the project that converts JAVA objects to JSON. If not, you need on. Try using Hymanson in your project.
项目中是否有将 JAVA 对象转换为 JSON 的转换器。如果没有,你需要。尝试在您的项目中使用 Hymanson。
Once Hymanson jars are imported into the project, the dispatcher servlet should have below:
将 Hymanson jar 导入项目后,调度程序 servlet 应具有以下内容:
<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.MappingHymanson2HttpMessageConverter">
</beans:bean>
回答by Mike Thomsen
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.
尝试将 @ResponseBody 添加到方法签名中 REST 方法的返回类型声明中。如果您使用标准的 Spring Boot 启动项目,应该这样做。