1. 程式人生 > >前臺如何獲取列舉型別的值

前臺如何獲取列舉型別的值

用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>
</html>

師兄說:飢餓能讓腦子變清醒!每當迷茫的時候,他都會餓自己兩天,之後就知道自己到底想要什麼了。

我最近也迷茫了,照做了。師兄沒有騙我,餓了兩天後,我也清楚的認識到自己究竟想要什麼啦。我想要吃飯。