使用@RequestBody传对象参数时碰到的坑

工作中需要使用到http接口传一个对象数组,网上找到某博客:springmvc参数为对象,数组
但是测试还是不对,报错:

2019-02-21 23:44:37.168  WARN 34133 --- [nio-7001-exec-6] 
.w.s.m.s.DefaultHandlerExceptionResolver : 
Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: 
JSON parse error: 
Can not construct instance of com.cainiao.cngdm.domain.common.Report: no String-argument constructor/factory method to deserialize from String value ('{"title":"11","note":"22","goodsList":[{"goodsNumber":"001","goodsName":"商品A"},{"goodsNumber":"002","goodsName":"商品B"}]}'); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.cainiao.cngdm.domain.common.Report: no String-argument constructor/factory method to deserialize from String value ('{"title":"11","note":"22","goodsList":[{"goodsNumber":"001","goodsName":"商品A"},{"goodsNumber":"002","goodsName":"商品B"}]}')

看样子好像时说少了string参数的构造函数,试过很多其他办法还不行后,决定试一下增加一个String类型的构造方法,代码如下:

public class Report  implements Serializable {

	private static final long serialVersionUID = 1L;
	String title;
	String note;
	List<Goods> goodsList;

	Report(){}
	Report(String dd) {
		Report report = JSON.parseObject(dd,Report.class);
		this.title=report.title;
		this.note=report.title;
		this.goodsList=report.goodsList;
	}

	//getter... setter...
}
public class Goods  implements Serializable {

	private static final long serialVersionUID = 1L;

	String goodsNumber;
	String goodsName;
	//getter... setter...
}

PS:@RequestBody的使用需要加载MappingJackson2HttpMessageConverter,但是SpringBoot的官方文档提到,这个是默认已经加载的了,所以最后spring的配置这部分我又删了,测试OK。
上面是测试代码,测试代码测通后,我的代码还是报错,我的真实代码是这样的:

	@RequestMapping("/addReportDo")
    @ResponseBody
    public String addReportDo(String title,String note,@RequestBodyList<Goods> goodsList){
        System.out.println(report);
        return "ok";
    }
//错误代码
2019-02-22 12:05:28.498  WARN 36431 --- [nio-7001-exec-7] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: 
org.springframework.http.converter.HttpMessageNotReadableException: 
JSON parse error: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token; 
nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token

大概意思是不能从这个String转到List,也就是list对应jsonArray格式不对,使用对象像上面一样封装起来Report就OK了。也就是下面的区别:

{goodsList: [{
    	goodsNumber: "001",
    	goodsName: "商品A"
	},{
    	goodsNumber: "002",
    	goodsName: "商品B"
	}]
}
{[{
    	goodsNumber: "001",
    	goodsName: "商品A"
	},{
    	goodsNumber: "002",
    	goodsName: "商品B"
	}]
}

以上观点由于时间原因,只是记录一下现象和解决方案,具体原因还没有细看springMVC里的json处理是怎么进行的,希望看到的同仁们有相似问题的可以一起探讨!

你可能感兴趣的:(spring)