下面是一个测试接口:返回一个枚举
package com.cn.yjf.server.controller;
import com.alibaba.fastjson.JSONObject;
import com.cn.yjf.common.enums.ResponseCodeEnum;
import com.cn.yjf.common.response.ResultModel;
import com.cn.yjf.server.dao.TsysAccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class TsysAccountController {
@PostMapping("/getEnums")
public ResultModel getEnums(){
return ResultModel.success(ResponseCodeEnum.SUCCESS);
}
}
返回结果:
结果结构上不对,应该是data:{Enum} 这样的结构。
对枚举类型进行序列化:
@JsonFormat(shape = JsonFormat.Shape.OBJECT) //将枚举类型序列化为对象
package com.cn.yjf.common.enums;
import com.fasterxml.jackson.annotation.JsonFormat;
/**
* 作为响应请求的枚举
* Created by QSJ on 2018/11/29.
*/
@JsonFormat(shape = JsonFormat.Shape.OBJECT) //将枚举类型序列化为对象
public enum ResponseCodeEnum {
SUCCESS(200, "SUCCESS"),
WARN(10000, "WARN"),
WARN_OPERATOR(10001, "WARN"),
TOKEN_ERROR(400, "TOKEN_ERROR"),
ERROR(300, "ERROR");
private Integer code;
private String messageKey;
private ResponseCodeEnum(Integer code, String messageKey) {
this.code = code;
this.messageKey = messageKey;
}
public Integer getCode() {
return this.code;
}
public String getMessageKey() {
return this.messageKey;
}
public void setMessageKey(String messageKey) {
this.messageKey = messageKey;
}
}
再次请求查看返回结果:
结构达到预期。