将对象转换为 json 控制字段名称大写首字母

Converting object to json control fields name upper case first letter

对象:

@XmlRootElement
public class AccountSyncResponse 
{
        private String Result;
        private String Value;

        public AccountSyncResponse() {}            

        public String getResult() {return Result;}
        public void setResult(String Result) {this.Result = Result;}
        public String getValue() {return Value;}
        public void setValue(String Value) {this.Value = Value;}        
}

休息网络服务:

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public AccountSyncResponse excute(AccountSyncRequest ASReq) 
    {        
       AccountSyncResponse ASRes = new AccountSyncResponse();
       return ASRes;    
    }

结果是{"result":"Create","value":"123456"}

我需要字段名的第一个字母大写{"Result":"Create","Value":"123456"}

如何控制结果 json 字符串中的字段名称?

您可以使用 @XmlElement 如下所示:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class AccountSyncResponse  {

    @XmlElement(name = "Result")
    private String result;

    @XmlElement(name = "Value")
    private String value;

    // Default constructor, getters and setters
}

或者,您可以使用 @XmlElement 注释 getter(这样就不需要 @XmlAccessorType 注释)。


除了 JAXB 注释,您可能需要考虑 Jackson。它是 Java 的流行 JSON 解析器,can be used with Jersey. Then you can use @JsonProperty 相反(但是 Jackson 也可以使用 JAXB 注释)。

对于 Jackson,根据您的需要,您可以使用 PropertyNamingStrategy such as PropertyNamingStrategy.UpperCamelCaseStrategy