Java将枚举序列化为对象

下面是一个测试接口:返回一个枚举 

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;
    }

}

再次请求查看返回结果:

 

结构达到预期。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值