【问题标题】:Is there a way to serialize all values of an enum with JSON in Kotlin?有没有办法在 Kotlin 中使用 JSON 序列化枚举的所有值?
【发布时间】:2021-06-18 06:25:26
【问题描述】:

我有以下枚举:

enum class Difficulty {
    EASY, MEDIUM, HARD
}

我的 Rest API 以以下方式工作:我有类,每个类都有一个 classManagementService,它有助于列出每个响应。像这样:

@Service
class RecipeManagementService (@Autowired private val recipeRepository: RecipeRepository,
                               private val addRecipeRequestTransformer: AddRecipeRequestTransformer) {

    fun findAll(): List<RecipeResponse> = this.recipeRepository.findAll().map(Recipe::toRecipeResponse)

RecipeResource.kt

@RestController
@RequestMapping(value = [BASE_RECIPE_URL])
class RecipeResource(private val recipeManagementService: RecipeManagementService)
{
    @GetMapping
    fun findAll(): ResponseEntity<List<RecipeResponse>> = ResponseEntity.ok(this.recipeManagementService.findAll())

RecipeResponse.kt

data class RecipeResponse (var id:Long,
                           var name:String,
                           var ingredient:List<Ingredient>?,
                           var process:String?,
                           var category: List<Category>?,
                           var difficulty: Difficulty?)

我希望 /api/v1/difficulty 请求列出所有困难。有没有办法做到这一点?

【问题讨论】:

    标签: json spring-boot rest kotlin enums


    【解决方案1】:

    每个枚举类都有一个生成的values() 方法,您可以使用它来获取所有可能值的数组:

    val allDifficulties: Array<Difficulty> = Difficulty.values()
    

    所以你可以在你的控制器中返回它,或者如果你想返回一个List,可以使用toList()

    【讨论】:

      猜你喜欢
      • 2010-09-14
      • 1970-01-01
      • 2015-03-17
      • 1970-01-01
      • 2022-11-30
      • 1970-01-01
      • 2014-02-17
      • 1970-01-01
      • 2014-09-11
      相关资源
      最近更新 更多