一, 需求:
页面返回数据
- {
- "code": 0,
- "msg": "",
- "count": "2",
- "data": [{
- "keywords": "广东木材提供有限公司 1",
- "frequency": 4621,
- "userNums": 4235
- },
- {
- "keywords": "广东木材提供有限公司 2",
- "frequency": 4621,
- "userNums": 4235
- }]
- }
二, 为此写了一个 Firm 类
- public class Firm {
- private String keywords;
- private String frequency;
- private String userNums;
- public Testdata(String keywords, String frequency, String userNums) {
- this.keywords = keywords;
- this.frequency = frequency;
- this.userNums = userNums;
- }
- }
三, 在 Controller 方法中
- @RequestMapping("/firm/listdata.action")
- public @ResponseBody Map<String, Object> listData(){
- List<Testdata> tdList = new ArrayList<>();
- Testdata td1 = new Testdata("广东木材提供有限公司 1","4621","4235");
- Testdata td2 = new Testdata("广东木材提供有限公司 1","4621","4235");
- tdList.add(td1);
- tdList.add(td2);
- tdList.add(td3);
- tdList.add(td4);
- tdList.add(td5);
- Map<String, Object> map = new HashMap<>();
- map.put("code", 0);
- map.put("msg", "");
- map.put("count", 2);
- map.put("data", tdList);
- return map;
- }
四, 访问时浏览器报 500 异常
- org.springframework.http.converter.HttpMessageNotWritableException:
- Could not write content: No serializer found for class cn.ssm.trading.domain.Firm and
- no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) )
- (through reference chain: java.util.HashMap["data"]->java.util.ArrayList[0]);
- nested exception is com.fasterxml.jackson.databind.JsonMappingException:
- No serializer found for class cn.ssm.trading.domain.Firm and no properties discovered to create BeanSerializer
- (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) )
- (through reference chain: java.util.HashMap["data"]->java.util.ArrayList[0])
五, 解决
为 Firm 类实现序列化, 为字段提供 getter/setter 以及无参构造方法
- public class Firm implements Serializable {
- private String keywords;
- private String frequency;
- private String userNums;
- public String getKeywords() {
- return keywords;
- }
- public void setKeywords(String keywords) {
- this.keywords = keywords;
- }
- public String getFrequency() {
- return frequency;
- }
- public void setFrequency(String frequency) {
- this.frequency = frequency;
- }
- public String getUserNums() {
- return userNums;
- }
- public void setUserNums(String userNums) {
- this.userNums = userNums;
- }
- // 无参构造方法
- public Testdata() {
- }
- public Testdata(String keywords, String frequency, String userNums) {
- this.keywords = keywords;
- this.frequency = frequency;
- this.userNums = userNums;
- }
- }
来源: http://www.bubuko.com/infodetail-2693588.html