用springmvc+fastjson如何传递枚举类型吗?

下面是测试用的枚举类:

通常的做法我们只能取出A或B....

    public enum TestEnum{
     
        A(1, "1-100"),
        B(2,"2-200"),
        C(3, "3-300"),
        D(4, "4-400"),
        E(5, "5-500");
     
        private Integer code;
        private String desc;
     
        TestEnum(Integer code, String desc) {
            this.code = code;
            this.desc = desc;
        }
     
        public Integer getCode() {
            return code;
        }
        public String getDesc() {
            return desc;
        }
     
    }

统一返回的包装类:

    public class Result {
     
        private Integer id;
     
        private TestEnum testEnum;
     
        public Integer getId() {
            return id;
        }
     
        public void setId(Integer id) {
            this.id = id;
        }
     
        public TestEnum getTestEnum() {
            return testEnum;
        }
     
        public void setTestEnum(TestEnum testEnum) {
            this.testEnum = testEnum;
        }
     
        public Result(Integer id, TestEnum testEnum) {
            this.id = id;
            this.testEnum = testEnum;
        }
     
    }

两种方法:

第一种:在Controller中直接操作

    @Controller
     
    public class TestController {
     
        @RequestMapping("/")
        public String home(Model model){
            return "index";
        }
     
        @RequestMapping("/ajax")
        @ResponseBody
        public String ajax(){
            SerializeConfig config = new SerializeConfig();
            config.configEnumAsJavaBean(TestEnum.class);
            Result result = new Result(100, TestEnum.A);
            return JSON.toJSONString(result,config);
        }
    }

 

    <%@ page language="java" contentType="text/html; charset=utf-8"
             pageEncoding="utf-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <body>
    <h2>Hello World!</h2>
    <body>
    <div>
        测试
    </div>
    <script type="text/javascript" src="http://cdn.bootcss.com/jquery/3.1.0/jquery.min.js"></script>
    <script>
        $.ajax({
            url:"/ajax",
            type:"POST",
            contentType:"application/x-www-form-urlencoded",
            success:function (data) {
                alert(data.testEnum.desc);
            }
        });
     
    </script>
    </body>
    </body>
    </html>

 

第二种:通过toString()方法和配置文件操作

(1)springmvc.xml添加转换配置

        <!-- 注解驱动 -->
        <mvc:annotation-driven>
            <mvc:message-converters>
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <constructor-arg value="UTF-8" index="0"/><!--避免出现乱码 -->
                    <property name="supportedMediaTypes">
                        <list>
                            <value>application/json;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
                <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>text/html;charset=UTF-8</value>
                            <value>application/json</value>
                        </list>
                    </property>
                    <property name="fastJsonConfig">
                        <bean class="com.alibaba.fastjson.support.config.FastJsonConfig">
                            <property name="features">
                                <list>
                                    <value>AllowArbitraryCommas</value>
                                    <value>AllowUnQuotedFieldNames</value>
                                </list>
                            </property>
                            <property name="charset" value="UTF-8"/>
                            <property name="dateFormat" value="yyyy-MM-dd HH:mm:ss"/>
                            <property name="serializerFeatures">
                                <list>
                                    <value>WriteDateUseDateFormat</value>
                                    <!--消除对同一对象循环引用的问题,默认为false-->
                                    <value>DisableCircularReferenceDetect</value>
                                    <!--关键-->
                                    <value>WriteEnumUsingToString</value>
                                </list>
                            </property>
                        </bean>
                    </property>
                </bean>
            </mvc:message-converters>
        </mvc:annotation-driven>

 

(2)重写枚举类的toString()

    public enum TestEnum{
     
        //省略。。。
     
        @Override
        public String toString() {
            return "{'code':'"+this.code+"','desc':'"+this.desc+"'}";
        }
     
       //不要把单引号改成\双引号,这样当返回给前端json字符串,json字符串转成对象时会报格式不正确的错误:
        // @Override
        // public String toString() {
        // return "{\"code\":"+this.code+",\"desc\":"+this.desc+"}";
        // }
     
    }

(3)控制层

    @Controller
     
    public class TestController {
     
        @RequestMapping("/")
        public String home(Model model){
            return "index";
        }
     
        @RequestMapping("/ajax")
        @ResponseBody
        public Result ajax(){
            Result result = new Result(100, TestEnum.A);
            return result;
        }
     
    }

(4)前台页面取值

    <%@ page language="java" contentType="text/html; charset=utf-8"
             pageEncoding="utf-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <body>
    <h2>Hello World!</h2>
    <body>
    <div>
        测试
    </div>
    <script type="text/javascript" src="http://cdn.bootcss.com/jquery/3.1.0/jquery.min.js"></script>
    <script>
     
        $.ajax({
            url:"/ajax",
            type:"POST",
            contentType:"application/x-www-form-urlencoded",
            success:function (data) {
                alert(data);
                var jsonObject =eval("("+ data +")");
                alert(jsonObject.testEnum);
                var testEnum = jsonObject.testEnum;
                var em =eval('('+ testEnum +')');
                //这一步使用“var em =JSON.parse(testEnum);”也会发生错误。
                alert(em.desc);
            }
        });
    </script>
    </body>
    </body>

---------------------
作者:舟天91
来源:CSDN
原文:https://blog.csdn.net/qq_37859811/article/details/82110726
版权声明:本文为博主原创文章,转载请附上博文链接!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值