[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
最近做项目用到了spring的新特性@RequestBody,非常好用,客户端发送的json串直接给转换并且注入给bean,以前自己用都是按照SUN的java命名规范进行的项目开发,没发觉有什么异常。
给客户做项目,得按照客户的需求来,客户的需求是不受什么规范约束的,恰好客户给的需求是json串里面的变量名首字母全是大写,囧,如果按照常规java命名规则的话这是给class命名的方法。
等到做出几个接口之后,自己测试时,发现用@RequestBody死活将客户端传过来的变量赋不到相应的bean中,一时的感觉真是有点无奈,客户不按规则出牌,自己必须给他的不按规则买单。
经过思考,通常的Controller类是可以自己指定名字的,指定的方法就是@Controller("XXX"),那么与json串对应的bean里面的变量应该也是可以自用指定名字的,经过一番搜索终于找到了答案。
1.正确的处理方法:
给每个属性指定别名,指定的方法与controller类似,如下:
public class User { @JsonProperty(value = "Name") private String name;
@JsonProperty(value = "Age") private int age; } 经过指定相应的名字后,我遇到的问题就被解决了。
2.分析出现错误的原因:
由于注入时,使用的是setName(...),setSex(...),按照java的命名规范,对应的变量,name和sex会被赋值,但是如果变量命名为Name和Sex的话,
虽然生成的setter函数依然是setName(...),setSex(...),但是
spring框架注入时就无法分辨到底是name还是Name,依然会按照命名规则来,所以依然会给name赋值,如果恰好没有按照命名规则来,使用的是Name的话,就无法完成注入。
3.结论:
编写java在没有其他原因的情况下,最还还是按照java编程规范来编写,毕竟是一套约定俗成的规则,大家都在按照这个规则在做事,如果不按常理出牌,那么出问题是不可避免的,出了这种问题解决起来也是相当的麻烦,毕竟spring框架不是谁都能改的。