請求引數轉換為列舉型別

2021-10-12 08:43:36 字數 1757 閱讀 1163

在之前我們寫了一篇 實體類通過配置實現實體類列舉型別的轉換,提高了**的可讀性 鏈結位址

今天我想要把請求的引數,轉換為列舉型別,如下圖案例**所示

/**

* @author f

* curl example:

* curl -x get localhost:9999/type?type=1

*/@restcontroller

public

class

enumconvertcontroller

("/"

)public string typebypathvariable

(@pathvariable

("type"

) typeenum typeenum)

("/status"

)public string status

(@requestparam

("status"

) statusenum statusenum)

}

首先我們先提供乙個基礎父列舉

public

inte***ce

baseenum

然後實現乙個型別列舉typeenum

import com.fasterxml.jackson.annotation.jsonvalue;

public

enum typeenum implements

baseenum

@override

public

intcode()

}

配置乙個轉換工具類

@component

public

class

requestfieldtoenumconvert

baseenum

>

implements

converter

public

requestfieldtoenumconvert

(class

enumtype)

}@override

public t convert

(string source)

return t;

}}

配置請求字段列舉轉換工廠

@component

public

class

requestfieldtoenumconvertfactory

implements

converte***ctory

return converter;

}}

然後我們需要把轉換工廠配置到mvc配置中,作為轉換配置

@configuration

public

class

webmvcconfig

implements

webmvcconfigurer

@override

public

void

addformatters

(formatterregistry registry)

}

現在讓我們來看看成果

字串轉換為列舉和整數轉換為列舉

假設定義了乙個這樣的列舉型別 enum myenum 1 字串轉換為列舉 string stra aa myenum myenum myenum enum.parse typeof myenum stra 上面的方法是區分大小寫的,也就是說,如果stra的值為 aa 則轉換失敗 如果不需要區分大小寫...

列舉值轉換(字串轉換為列舉和整數轉換為列舉)

列舉值轉換 字串轉換為列舉和整數轉換為列舉 假設定義了乙個這樣的列舉型別 enum myenum 1 字串轉換為列舉 string stra aa myenum myenum myenum enum.parse typeof myenum stra 上面的方法是區分大小寫的,也就是說,如果stra的...

列舉型別轉換

列舉型別轉換成int型別 例 1 public enum gender26 7 gender gender gender.男 8int a gender 9 console.writeline a 輸入結果 0還有乙個功能 1 public enum gender26 7 gender gender...