且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JAVA对象jackson序列化json属性名首字母变成小写的解决方案

更新时间:2021-07-13 19:32:49

java代码对象如下:

package com.ctrip.market.messagepush.service.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

public class WaitSendModel {


    public long MsgID;

    public String GroupID;

    public int SendLevel;

    public int SendType;

    public long getMsgID() {
        return MsgID;
    }

    public void setMsgID(long msgID) {
        this.MsgID = msgID;
    }

    public String getGroupID() {
        return GroupID;
    }

    public void setGroupID(String groupID) {
        this.GroupID = groupID;
    }

    public int getSendLevel() {
        return SendLevel;
    }

    public void setSendLevel(int sendLevel) {
        this.SendLevel = sendLevel;
    }

    public int getSendType() {
        return SendType;
    }

    public void setSendType(int sendType) {
        this.SendType = sendType;
    }
}

执行结果,首字母小写:

Json={"msgID":100005,"groupID":"00001","sendLevel":5}

以上的对象如果通过jackson转成json格式的话,首字母会自动变成小写,如果我想让首字母变成大写的,该如何处理呢?

在属性上加@JsonProperty 注解,并且在对应的setter ,getter 上面加上@JsonIgnore,这样就可以了,添加完之后的代码如下:

package com.ctrip.market.messagepush.service.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;


public class WaitSendModel {

    @JsonProperty
    public long MsgID;


    @JsonProperty
    public String GroupID;


    @JsonProperty
    public int SendLevel;


    @JsonProperty
    public int SendType;

    @JsonIgnore
    public long getMsgID() {
        return MsgID;
    }

    @JsonIgnore
    public void setMsgID(long msgID) {
        this.MsgID = msgID;
    }
    @JsonIgnore
    public String getGroupID() {
        return GroupID;
    }
    @JsonIgnore
    public void setGroupID(String groupID) {
        this.GroupID = groupID;
    }
    @JsonIgnore
    public int getSendLevel() {
        return SendLevel;
    }
    @JsonIgnore
    public void setSendLevel(int sendLevel) {
        this.SendLevel = sendLevel;
    }
    @JsonIgnore
    public int getSendType() {
        return SendType;
    }
    @JsonIgnore
    public void setSendType(int sendType) {
        this.SendType = sendType;
    }
}

执行结果,首字母大写:

Json={"MsgID":100005,"GroupID":"00001","SendLevel":5,"SendType":0}