JSONObject.toJSONString首字母大小写问题的三种解决方案

1、在字段上加注解@JSONField

package com.cjh.wechatmp.po;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import lombok.NoArgsConstructor;

@NoArgsConstructor
@Data
public class InMessageText {

    @JSONField(name = "ToUserName")
    private String ToUserName;
    @JSONField(name = "FromUserName")
    private String FromUserName;
    private String CreateTime;
    private String MsgType;
    private String Content;
    private String MsgId;
}

优点:少量的话简单方便

缺点:入侵性强,懒得每个加

2、自定义配置

优点: 逼格高

缺点:并不是忽略不转,而是转了小写,再转回来大写

package com.wechat.util;

import java.util.Map;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.JavaIdentifierTransformer;
import net.sf.json.util.PropertySetStrategy;

public class JsonUtil {

    public static Object toBean(JSONObject jsonObject, Class rootClass,
        String[] ignoreLowercase, Map childClass) {
        JsonConfig config = new JsonConfig();

        //转换对象
        config.setRootClass(rootClass);

        //首字母小写
        config.setJavaIdentifierTransformer(new JavaIdentifierTransformer() {
            @Override
            public String transformToJavaIdentifier(String str) {
                if (ignoreLowercase.length > 0) {
                    for (String item : ignoreLowercase) {
                        if (str.indexOf(item) == 0) {
                            return str;
                        }
                    }
                }
                char[] chars = str.toCharArray();
                chars[0] = Character.toLowerCase(chars[0]);
                return new String(chars);
            }
        });

        //对象里没有的属性忽略
        config.setPropertySetStrategy(new PropertySetStrategy() {
            @Override
            public void setProperty(Object o, String s, Object o1) throws JSONException {
                try {
                    PropertySetStrategy.DEFAULT.setProperty(o, s, o1);
                } catch (JSONException e) {
                }
            }
        });

        //自定义的list声明
        if (childClass != null) {
            config.setClassMap(childClass);
        }

        return JSONObject.toBean(jsonObject, config);
    }

}

3、用Gson代替(推荐)

优点:简单方便

缺点:要添加依赖,不过不会和之前的冲突哦


    
      com.google.code.gson
      gson
      2.8.5
    

效果:

InMessageText(ToUserName=toUser, FromUserName=fromUser, CreateTime=1348831860, MsgType=text, Content=this is a test, MsgId=1234567890123456)

Gson--->{"ToUserName":"toUser","FromUserName":"fromUser","CreateTime":"1348831860","MsgType":"text","Content":"this is a test","MsgId":"1234567890123456"}
JSONObject--->{"content":"this is a test","createTime":"1348831860","fromUserName":"fromUser","msgId":"1234567890123456","msgType":"text","toUserName":"toUser"}

 

你可能感兴趣的:(java)