关于fastjson大小写转换问题的解决办法

  相信大家都有过,使用fastjson把java对象转换成json字符串,而对象里面大写开关的属性被转换成了小写。现在就在这里说下我用到的方法:

    首先来个错误的示范,一般大写的属性都会这样定义:


    @JSONField(name = "RequestMsg")
    private  RequestMsgEntity RequestMsg;


   public RequestMsgEntity getRequestMsg() {
        return RequestMsg;
    }


    public void setRequestMsg(RequestMsgEntity requestMsg) {
        RequestMsg = requestMsg;
    }

这样定义的属性,通过注解是找不到的,原因如下:

下面是com.alibaba.fastjson.util.TypeUtils里面一段的源码


 String propertyName = Character.toLowerCase(methodName.charAt(2)) + methodName.substring(3);


                Field field = ParserConfig.getField(clazz, propertyName);
                if (field != null) {
                    JSONField fieldAnnotation = field.getAnnotation(JSONField.class);


                    if (fieldAnnotation != null && fieldAnnotation.name().length() != 0) {
                        propertyName = fieldAnnotation.name();


                        if (aliasMap != null) {
                            propertyName = aliasMap.get(propertyName);
                            if (propertyName == null) {
                                continue;
                            }
                        }
                    }
                }


可以看到它在找field的时候是通过methodName来找的,而这里对首字母做了小写的处理,而我们定义的属性首字母是大写的导致这个注解找不到。

所以解决办法就是:

  @JSONField(name = "RequestMsg")
    private  RequestMsgEntity requestMsg;


    public RequestMsgEntity getRequestMsg() {
        return requestMsg;
    }


    public void setRequestMsg(RequestMsgEntity requestMsg) {
        this.requestMsg = requestMsg;
    }

我们将属性名称的首字母改成小写,这样就能找到注解,然后转换成json的时候就正确了。

就写这么多,希望能帮到大家!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值